Bird
Raised Fist0
Software Engineeringknowledge~10 mins

Creational patterns (Singleton, Factory, Builder) in Software Engineering - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Creational patterns (Singleton, Factory, Builder)
Start
↓
Need object creation
↓
Singleton
↓
One instance
↓
Use object
↓
End
The flow starts when an object is needed. You pick one of the three creational patterns: Singleton for one instance, Factory for creating objects based on input, or Builder for step-by-step construction. Then you use the created object.
Execution Sample
Software Engineering
class Singleton:
    _instance = None
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
This code creates a Singleton class that ensures only one instance exists.
Analysis Table
StepActionConditionResultInstance ID
1Call Singleton()_instance is NoneCreate new instanceID_1
2Call Singleton() again_instance is not NoneReturn existing instanceID_1
3Call Singleton() third time_instance is not NoneReturn existing instanceID_1
ExitNo more calls-All calls return same instanceID_1
💡 Singleton pattern stops creating new instances after the first one.
State Tracker
VariableStartAfter 1After 2After 3Final
_instanceNoneID_1ID_1ID_1ID_1
Key Insights - 3 Insights
Why does Singleton return the same instance every time?
Because after the first creation (_instance is set), the condition in step 2 and 3 returns false for creating new, so it returns the stored instance (see execution_table rows 2 and 3).
How does Factory pattern decide which object to create?
Factory uses input or parameters to choose which subclass or object to create, unlike Singleton which always returns one instance (not shown in table but conceptually different).
Why use Builder instead of directly creating an object?
Builder allows step-by-step construction of complex objects, useful when many parts or configurations are needed, unlike Singleton or Factory which create objects in one step.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the instance ID returned at step 3?
AID_1
BID_2
CNone
DNew instance created
💡 Hint
Check the 'Instance ID' column at step 3 in the execution_table.
At which step does the Singleton pattern create a new instance?
AStep 3
BStep 2
CStep 1
DExit
💡 Hint
Look at the 'Result' column to see when 'Create new instance' happens.
If the _instance variable started as ID_5 instead of None, what would happen at step 1?
ACreate new instance with ID_1
BReturn existing instance ID_5
CError because _instance is not None
DCreate multiple instances
💡 Hint
Refer to variable_tracker and execution_table step 1 condition checking _instance.
Concept Snapshot
Creational Patterns:
- Singleton: One instance only, reused everywhere.
- Factory: Creates objects based on input type.
- Builder: Builds complex objects step-by-step.
Use Singleton to save resources, Factory for flexible creation, Builder for complex setups.
Full Transcript
Creational patterns help create objects in software. Singleton ensures only one instance exists by checking if an instance already exists before creating a new one. Factory creates different objects based on input, allowing flexibility. Builder constructs complex objects stepwise, useful when many parts or configurations are needed. The execution table shows Singleton creating one instance at step 1 and returning the same instance later. Variables track the instance state. Key moments clarify why Singleton returns the same instance and differences with Factory and Builder. Quizzes test understanding of instance creation and reuse.

Practice

(1/5)
1. Which creational pattern ensures that only one instance of a class is created throughout the application?
easy
A. Singleton
B. Factory
C. Builder
D. Prototype

Solution

  1. Step 1: Understand the Singleton pattern purpose

    The Singleton pattern restricts the instantiation of a class to one object only.
  2. Step 2: Compare with other patterns

    Factory creates objects but does not limit the number; Builder constructs complex objects step-by-step; Prototype clones objects.
  3. Final Answer:

    Singleton -> Option A
  4. Quick Check:

    Only one instance = Singleton [OK]
Hint: Singleton = single instance only [OK]
Common Mistakes:
  • Confusing Factory with Singleton
  • Thinking Builder limits instances
  • Mixing Prototype with Singleton
2. Which of the following is the correct way to define a Singleton class in most object-oriented languages?
easy
A. Allow multiple instances but share data between them
B. Build the object step-by-step using a builder
C. Make the constructor private and provide a static method to get the instance
D. Use a factory method to create new instances every time

Solution

  1. Step 1: Recall Singleton implementation details

    Singleton classes hide their constructor (make it private) to prevent direct instantiation.
  2. Step 2: Provide controlled access

    A static method returns the single instance, creating it if it doesn't exist yet.
  3. Final Answer:

    Make the constructor private and provide a static method to get the instance -> Option C
  4. Quick Check:

    Private constructor + static getter = Singleton [OK]
Hint: Singleton hides constructor, uses static getter [OK]
Common Mistakes:
  • Allowing public constructors in Singleton
  • Using factory method to create multiple instances
  • Confusing Builder with Singleton syntax
3. Consider the following code snippet using a Factory pattern:
class AnimalFactory {
  createAnimal(type) {
    switch(type) {
      case 'dog': return new Dog();
      case 'cat': return new Cat();
      default: return null;
    }
  }
}

const factory = new AnimalFactory();
const pet = factory.createAnimal('dog');
console.log(pet.sound());

What will be the output if Dog.sound() returns "Woof" and Cat.sound() returns "Meow"?
medium
A. Error: createAnimal is not a function
B. "Meow"
C. null
D. "Woof"

Solution

  1. Step 1: Understand the Factory method call

    The factory creates an object based on the string 'dog', so it returns a new Dog instance.
  2. Step 2: Call the sound method on the Dog instance

    Since Dog.sound() returns "Woof", the console.log outputs "Woof".
  3. Final Answer:

    "Woof" -> Option D
  4. Quick Check:

    Factory creates Dog, Dog.sound() = "Woof" [OK]
Hint: Factory returns object by type, call its method [OK]
Common Mistakes:
  • Assuming factory returns null for known types
  • Confusing Dog and Cat outputs
  • Thinking createAnimal is undefined
4. A developer tries to implement a Singleton but writes this code:
class Logger {
  constructor() {
    if (!Logger.instance) {
      Logger.instance = this;
    }
    return Logger.instance;
  }
}

const log1 = new Logger();
const log2 = new Logger();
console.log(log1 === log2);

What is the output and what is the issue with this Singleton implementation?
medium
A. false; constructor allows multiple instances
B. true; but constructor is public which is not ideal
C. true; works perfectly as Singleton
D. Error; cannot assign to Logger.instance

Solution

  1. Step 1: Analyze the constructor logic

    The constructor checks if Logger.instance exists; if not, assigns this to it, then returns Logger.instance.
  2. Step 2: Check the instance equality

    Both log1 and log2 refer to the same Logger.instance, so log1 === log2 is true.
  3. Step 3: Identify the issue

    The constructor is still public, so new Logger() can be called multiple times, which is not ideal for Singleton pattern.
  4. Final Answer:

    true; but constructor is public which is not ideal -> Option B
  5. Quick Check:

    Same instance but public constructor = A [OK]
Hint: Singleton needs private constructor to prevent multiple calls [OK]
Common Mistakes:
  • Assuming public constructor is fine for Singleton
  • Thinking output is false due to new calls
  • Expecting runtime error on instance assignment
5. You need to create a complex computer object with many optional parts (CPU, RAM, GPU, Storage). Which creational pattern is best suited to build this object step-by-step without confusing the client code?
hard
A. Builder
B. Factory
C. Singleton
D. Prototype

Solution

  1. Step 1: Understand the problem requirements

    The object is complex with many optional parts, so building it step-by-step is needed.
  2. Step 2: Match with creational patterns

    Builder pattern is designed to construct complex objects step-by-step, allowing optional parts without confusing client code.
  3. Step 3: Exclude other patterns

    Singleton limits instances, Factory creates objects but not stepwise, Prototype clones existing objects.
  4. Final Answer:

    Builder -> Option A
  5. Quick Check:

    Step-by-step complex object = Builder [OK]
Hint: Builder builds complex objects stepwise clearly [OK]
Common Mistakes:
  • Choosing Singleton for complex object creation
  • Using Factory when stepwise building is needed
  • Confusing Prototype cloning with building
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard