Bird
Raised Fist0
Software Engineeringknowledge~6 mins

Creational patterns (Singleton, Factory, Builder) in Software Engineering - Full Explanation

Choose your learning style10 modes available
Introduction
Creating objects in software can be tricky when you want to control how many are made or how they are built. Without clear methods, programs can become messy or inefficient. Creational patterns help solve these problems by giving clear ways to create objects.
Explanation
Singleton Pattern
This pattern ensures that only one instance of a class exists throughout the program. It provides a global point of access to that instance, so everyone uses the same object. This is useful when exactly one object is needed to coordinate actions.
Singleton guarantees a single shared instance accessible globally.
Factory Pattern
The factory pattern creates objects without exposing the creation logic to the client. Instead, it uses a method or class to decide which object type to create based on input or conditions. This helps keep code flexible and easier to change.
Factory hides object creation details and decides which object to make.
Builder Pattern
Builder separates the construction of a complex object from its representation. It allows step-by-step creation of different parts, so the same process can create different types of objects. This is helpful when objects need many parts or options.
Builder creates complex objects step-by-step, allowing different representations.
Real World Analogy

Imagine a hotel where only one manager handles all bookings (Singleton). Guests don’t book rooms directly but go through a receptionist who decides which room to assign based on guest needs (Factory). For special suites, the hotel builds the room step-by-step with custom furniture and decorations (Builder).

Singleton Pattern → The hotel manager who is the only one managing bookings
Factory Pattern → The receptionist who chooses and assigns the right room type
Builder Pattern → The team that assembles a custom suite step-by-step
Diagram
Diagram
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│   Singleton   │──────▶│    Factory    │──────▶│    Builder    │
│  Single Obj   │       │ Creates Objects│       │ Step-by-step  │
└───────────────┘       └───────────────┘       └───────────────┘
Diagram shows the three creational patterns as connected boxes highlighting their roles in object creation.
Key Facts
Singleton Pattern → Ensures only one instance of a class exists and provides a global access point.
Factory Pattern → Creates objects without exposing the creation logic, deciding which type to create.
Builder Pattern → Constructs complex objects step-by-step, allowing different representations.
Creational Patterns → Design patterns focused on controlling object creation to increase flexibility and reuse.
Code Example
Software Engineering
class Singleton:
    _instance = None
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

class Product:
    def __init__(self, name):
        self.name = name

class Factory:
    @staticmethod
    def create_product(type_name):
        if type_name == 'A':
            return Product('Product A')
        elif type_name == 'B':
            return Product('Product B')
        else:
            return Product('Default Product')

class Builder:
    def __init__(self):
        self.product = Product('')
    def set_name(self, name):
        self.product.name = name
        return self
    def build(self):
        return self.product

# Using Singleton
s1 = Singleton()
s2 = Singleton()
print(s1 is s2)  # True

# Using Factory
p1 = Factory.create_product('A')
p2 = Factory.create_product('B')
print(p1.name)  # Product A
print(p2.name)  # Product B

# Using Builder
builder = Builder()
p3 = builder.set_name('Custom Product').build()
print(p3.name)  # Custom Product
OutputSuccess
Common Confusions
Singleton means no new objects can ever be created again.
Singleton means no new objects can ever be created again. Singleton means only one instance of a specific class exists, but other classes can still create multiple objects.
Factory pattern creates objects directly like calling a constructor.
Factory pattern creates objects directly like calling a constructor. Factory hides the creation details and decides which object to create, so clients don’t call constructors directly.
Builder pattern is just another way to write constructors.
Builder pattern is just another way to write constructors. Builder separates the construction process from the final object, allowing stepwise and flexible creation, unlike simple constructors.
Summary
Creational patterns help manage how objects are created to keep code clean and flexible.
Singleton ensures only one instance of a class exists and is shared globally.
Factory hides object creation details and decides which object to create based on input.
Builder allows building complex objects step-by-step, supporting different configurations.

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