Understanding Creational Patterns: Singleton, Factory, and Builder
📖 Scenario: You are learning about creational design patterns used in software engineering to create objects in different ways. These patterns help manage how objects are made, ensuring efficiency and flexibility in programs.Imagine you are designing a simple system that needs to create different types of vehicles. You want to understand how Singleton, Factory, and Builder patterns work by creating examples for each.
🎯 Goal: Build a simple example for each creational pattern: Singleton, Factory, and Builder. You will create a singleton class to ensure only one instance exists, a factory to create vehicle objects based on type, and a builder to assemble a complex vehicle step-by-step.
📋 What You'll Learn
Create a Singleton class called Logger that only allows one instance.
Create a Factory function called vehicle_factory that returns different vehicle objects based on a type string.
Create a Builder class called VehicleBuilder that constructs a vehicle by setting parts step-by-step.
Use clear and simple code to demonstrate each pattern.
💡 Why This Matters
🌍 Real World
Creational patterns are used in software development to control how objects are created, improving code organization and flexibility in real applications like game development, web services, and system design.
💼 Career
Understanding these patterns is essential for software engineers and developers to write maintainable and scalable code, and they are commonly asked about in technical interviews.
Progress0 / 4 steps
1
Create the Singleton class Logger
Write a class called Logger that ensures only one instance can be created. Use a class variable called _instance to store the single instance. In the __new__ method, check if _instance is None; if so, create and store the instance, otherwise return the existing one.
Software Engineering
Hint
Use a class variable to hold the single instance. Override __new__ to control instance creation.
2
Create the Factory function vehicle_factory
Write a function called vehicle_factory that takes a parameter vehicle_type. If vehicle_type is "car", return the string "Car object created". If vehicle_type is "bike", return "Bike object created". For any other value, return "Unknown vehicle".
Software Engineering
Hint
Use if, elif, and else to return different strings based on vehicle_type.
3
Create the Builder class VehicleBuilder
Write a class called VehicleBuilder with an __init__ method that initializes an empty dictionary called vehicle. Add methods set_wheels(self, number) and set_color(self, color) that add these keys and values to the vehicle dictionary. Add a method get_vehicle(self) that returns the vehicle dictionary.
Software Engineering
Hint
Use a dictionary to store vehicle parts. Add methods to set wheels and color, and a method to return the dictionary.
4
Complete the example by creating a vehicle using VehicleBuilder
Create an instance of VehicleBuilder called builder. Use builder.set_wheels(4) and builder.set_color("red") to set the vehicle parts. Finally, create a variable my_vehicle and assign it the result of builder.get_vehicle().
Software Engineering
Hint
Create the builder object, set wheels and color, then get the vehicle dictionary.
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
Step 1: Understand the Singleton pattern purpose
The Singleton pattern restricts the instantiation of a class to one object only.
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.
Final Answer:
Singleton -> Option A
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
Step 1: Recall Singleton implementation details
Singleton classes hide their constructor (make it private) to prevent direct instantiation.
Step 2: Provide controlled access
A static method returns the single instance, creating it if it doesn't exist yet.
Final Answer:
Make the constructor private and provide a static method to get the instance -> Option C
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
Step 1: Understand the Factory method call
The factory creates an object based on the string 'dog', so it returns a new Dog instance.
Step 2: Call the sound method on the Dog instance
Since Dog.sound() returns "Woof", the console.log outputs "Woof".
Final Answer:
"Woof" -> Option D
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
Step 1: Analyze the constructor logic
The constructor checks if Logger.instance exists; if not, assigns this to it, then returns Logger.instance.
Step 2: Check the instance equality
Both log1 and log2 refer to the same Logger.instance, so log1 === log2 is true.
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.
Final Answer:
true; but constructor is public which is not ideal -> Option B
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
Step 1: Understand the problem requirements
The object is complex with many optional parts, so building it step-by-step is needed.
Step 2: Match with creational patterns
Builder pattern is designed to construct complex objects step-by-step, allowing optional parts without confusing client code.
Step 3: Exclude other patterns
Singleton limits instances, Factory creates objects but not stepwise, Prototype clones existing objects.