Course contentsShow
← Software Engineering
Lesson 247 of 1,9337. Creational Design PatternsFree lesson

The Prototype Pattern: Cloning Objects

Learn how Prototype creates new objects by copying existing instances rather than constructing from scratch.

The Prototype Pattern: Cloning Objects

What you'll learn: How the Prototype pattern creates new objects by copying existing instances instead of building them from scratch.

The Core Idea

Sometimes creating an object from zero is expensive or complicated. You might need to set dozens of properties, run complex initialization logic, or load external resources. The Prototype pattern solves this by keeping a fully-configured "prototype" object around and cloning it whenever you need a new instance.

Think of it like a cookie cutter: instead of mixing ingredients from scratch every time, you press the cutter into dough that's already prepared. The pattern works the same way—you duplicate an existing object rather than constructing a new one step-by-step.

When to Use Prototype

This pattern shines when:

  • Object creation is costly (database queries, file loading, complex calculations)
  • You have several variations of similar objects
  • You want to avoid the complexity of Factory hierarchies for simple cases
  • The new object should start with the same state as an existing one

How It Differs from Other Creational Patterns

Unlike Builder (which constructs step-by-step) or Factory Method (which delegates to subclasses), Prototype focuses on duplication. You ask an existing object, "Make me a copy of yourself." The object knows its own structure, so it can create an accurate clone.

The Clone Operation

The pattern typically involves a clone() method that returns a copy of the object. The challenge is deciding between shallow copying (copying references) versus deep copying (copying the actual nested objects too).

Key Takeaway: The Prototype pattern creates new objects by cloning existing instances rather than constructing from scratch, which is especially useful when object creation is expensive or when you need multiple similar configurations.