Skip to main content

What is the Prototype pattern?

Prototype is a creational design pattern that lets you create new objects by cloning existing ones, instead of building them from scratch through a constructor.


1. The core idea

Instead of creating an object anew and manually initializing every field, you can take a ready instance (a prototype) and copy it. This is especially useful when creating an object is:

  • expensive (requires complex initialization, network or file operations),
  • or the object is already configured the way you need, and it is simpler to duplicate it.

2. When to use it

  • When the process of creating objects is complex or resource-intensive.
  • When you need to copy objects with individual settings.
  • When the system must be independent of the concrete classes of the objects being created (for example, duplicates of different types).

3. Structure

  1. Prototype (interface) - declares a clone() method.
  2. ConcretePrototype - implements clone() and returns a copy of itself.
  3. Client - works with objects through the Prototype interface, without knowing which exact class is being cloned.

4. Example (Java)

java
interface Prototype { Prototype clone(); } class Shape implements Prototype { int x, y; String color; public Shape clone() { Shape copy = new Shape(); copy.x = this.x; copy.y = this.y; copy.color = this.color; return copy; } }

Usage:

java
Shape original = new Shape(); original.x = 10; original.y = 20; original.color = "red"; Shape copy = (Shape) original.clone();

Now copy is a new object with the same properties, but independent of the original.


5. Advantages

  • Removes the need to write bulky constructors.
  • Lets you duplicate complex objects without knowing their internal structure.
  • Speeds up creating objects of the same type.
  • Simplifies adding new types without changing the client code.

6. Disadvantages

  • Copying must be implemented carefully, especially when there are nested objects (deep copying).
  • It can be unclear which fields are copied and which remain references.
  • Requires extra control over memory and state when dependencies are complex.

Summary: Prototype is a way to create new objects by copying existing ones, providing flexibility, speed, and independence from concrete classes when creating instances.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.