Bird
Raised Fist0
LLDsystem_design~7 mins

Prototype pattern in LLD - System Design Guide

Choose your learning style10 modes available
Problem Statement
Creating new objects by initializing them from scratch can be slow and error-prone, especially when many objects share similar properties. This leads to duplicated code and inconsistent object states when copying manually.
Solution
The Prototype pattern solves this by cloning existing objects to create new ones. Instead of building from zero, it copies a prototype object and then modifies it if needed, ensuring consistency and saving time.
Architecture
Client
→Prototype
↓
Cloned Object
Cloned Object

This diagram shows the client requesting a clone from the prototype object, which returns a new cloned object.

Trade-offs
✓ Pros
→
Speeds up object creation by copying existing instances.
→
Ensures new objects start with a consistent state.
→
Reduces subclassing by cloning different prototypes.
→
Simplifies object creation when constructors are complex.
✗ Cons
→
Cloning complex objects with deep references can be tricky and error-prone.
→
Requires careful implementation of clone methods to avoid shared mutable state.
→
May increase memory usage if many prototypes are kept in memory.
Use when object creation is costly or complex, and many similar objects are needed quickly, especially if they differ only slightly.
Avoid when objects are simple to create or when cloning deep object graphs is too complex or risky.
Real World Examples
Adobe
Uses prototype pattern in Photoshop to quickly duplicate complex image objects with many properties.
Unity
Game engine uses prototype pattern to clone game objects during runtime for performance and flexibility.
Google
In Google Docs, prototype pattern helps duplicate document elements efficiently while preserving formatting.
Code Example
Before applying the Prototype pattern, copying an object requires manually creating a new instance and copying each attribute, which is error-prone and verbose. After applying the pattern, the clone method uses deep copy to create a new object with the same state, simplifying object creation and ensuring consistency.
LLD
### Before Prototype Pattern (manual copy)
class Car:
    def __init__(self, model, color, options):
        self.model = model
        self.color = color
        self.options = options

car1 = Car('Sedan', 'Red', ['GPS', 'Sunroof'])

# Manual copy
car2 = Car(car1.model, car1.color, list(car1.options))

### After Prototype Pattern (using clone method)
import copy

class CarPrototype:
    def __init__(self, model, color, options):
        self.model = model
        self.color = color
        self.options = options

    def clone(self):
        return copy.deepcopy(self)

car1 = CarPrototype('Sedan', 'Red', ['GPS', 'Sunroof'])
car2 = car1.clone()
OutputSuccess
Alternatives
Factory Method
Creates objects by calling a factory method instead of cloning existing instances.
Use when: Use when object creation logic varies by subclass and cloning is not suitable.
Builder
Constructs complex objects step-by-step rather than cloning a prototype.
Use when: Use when object construction requires multiple steps or configurations.
Summary
Prototype pattern creates new objects by cloning existing ones to save time and ensure consistency.
It is useful when object creation is costly or complex and many similar objects are needed.
Careful implementation is required to handle deep copying and avoid shared mutable state.

Practice

(1/5)
1. What is the main purpose of the Prototype pattern in system design?
easy
A. To manage object creation through a factory
B. To enforce a single instance of a class
C. To separate interface from implementation
D. To create new objects by copying existing ones

Solution

  1. Step 1: Understand the Prototype pattern concept

    The Prototype pattern focuses on creating new objects by cloning existing ones instead of building from scratch.
  2. Step 2: Compare with other design patterns

    Singleton enforces one instance, Factory manages creation but not cloning, and Adapter separates interface from implementation.
  3. Final Answer:

    To create new objects by copying existing ones -> Option D
  4. Quick Check:

    Prototype pattern = cloning objects [OK]
Hint: Prototype means copy existing object, not create new from zero [OK]
Common Mistakes:
  • Confusing Prototype with Singleton pattern
  • Thinking Prototype creates objects from scratch
  • Mixing Prototype with Factory pattern
2. Which of the following is the correct way to declare a clone method in a prototype interface?
easy
A. public void clone();
B. public Object clone();
C. public Object copy();
D. public void copy();

Solution

  1. Step 1: Identify the clone method signature

    The clone method should return a new object copy, so it must return an Object type.
  2. Step 2: Check method return type and name

    Only public Object clone(); correctly returns a cloned object. Void return types or different method names are incorrect.
  3. Final Answer:

    public Object clone(); -> Option B
  4. Quick Check:

    Clone method returns Object [OK]
Hint: Clone returns a new object, so return type must not be void [OK]
Common Mistakes:
  • Using void return type for clone method
  • Naming method copy instead of clone
  • Not returning the cloned object
3. Given the following code snippet, what will be the output?
class Shape {
  int x, y;
  Shape(int x, int y) { this.x = x; this.y = y; }
  Shape clone() { return new Shape(x, y); }
}

Shape original = new Shape(5, 10);
Shape copy = original.clone();
System.out.println(copy.x + "," + copy.y);
medium
A. 5,10
B. 0,0
C. null,null
D. Compilation error

Solution

  1. Step 1: Understand the clone method behavior

    The clone method creates a new Shape object with the same x and y values as the original.
  2. Step 2: Trace the output of print statement

    Since original has x=5 and y=10, the cloned copy will also have these values, so output is "5,10".
  3. Final Answer:

    5,10 -> Option A
  4. Quick Check:

    Clone copies values correctly [OK]
Hint: Clone copies fields, so output matches original's values [OK]
Common Mistakes:
  • Assuming clone returns null
  • Expecting default values 0,0 instead of copied values
  • Thinking clone causes compile error
4. Identify the error in this prototype clone method implementation:
class Document {
  String content;
  Document(String content) { this.content = content; }
  Document clone() {
    Document copy = this;
    return copy;
  }
}
medium
A. clone method returns the same object reference instead of a new copy
B. clone method should return void
C. clone method should not be inside the class
D. clone method should throw an exception

Solution

  1. Step 1: Analyze the clone method implementation

    The method assigns this to copy, so it returns the same object reference, not a new object.
  2. Step 2: Understand prototype cloning requirement

    Prototype pattern requires returning a new object copy, not the original reference.
  3. Final Answer:

    clone method returns the same object reference instead of a new copy -> Option A
  4. Quick Check:

    Clone must return new object, not this [OK]
Hint: Clone must create new object, not return this [OK]
Common Mistakes:
  • Returning this instead of new object
  • Changing return type to void
  • Thinking clone must throw exception
5. You need to design a system where creating a complex object from scratch is expensive. Which approach best uses the Prototype pattern to improve performance?
hard
A. Use a Factory pattern to create new objects with different parameters
B. Create a new object from scratch every time to ensure uniqueness
C. Create a prototype object once and clone it whenever a new object is needed
D. Use a Singleton to share the same object instance everywhere

Solution

  1. Step 1: Identify the problem of expensive object creation

    Creating complex objects from scratch is costly in time or resources.
  2. Step 2: Apply Prototype pattern for efficient object creation

    By creating one prototype object and cloning it, we avoid repeated expensive construction.
  3. Step 3: Compare other options

    Singleton shares one instance, not copies; Factory creates new objects but may be costly; creating from scratch every time is inefficient.
  4. Final Answer:

    Create a prototype object once and clone it whenever a new object is needed -> Option C
  5. Quick Check:

    Prototype pattern = clone prototype to save cost [OK]
Hint: Clone prototype once, reuse clones to save creation cost [OK]
Common Mistakes:
  • Using Singleton instead of cloning
  • Creating new objects from scratch every time
  • Confusing Factory with Prototype
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