0
0
Software Engineeringknowledge~6 mins

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

Choose your learning style9 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 PatternEnsures only one instance of a class exists and provides a global access point.
Factory PatternCreates objects without exposing the creation logic, deciding which type to create.
Builder PatternConstructs complex objects step-by-step, allowing different representations.
Creational PatternsDesign 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.