Course contentsShow
← Computer Science
Lesson 2272 of 2,87251. Design PatternsFree lesson

Prototype Pattern and Cloning

Creating new objects by copying existing prototypes, useful when instantiation is expensive or complex.

Prototype Pattern and Cloning

What you'll learn: How to create new objects by copying existing ones instead of building them from scratch.

The Core Problem

Sometimes creating a new object is expensive—maybe it requires database queries, complex calculations, or intricate configuration. The Prototype Pattern solves this by letting you copy (clone) an already-configured object instead of re-initializing everything.

Think of it like photocopying a filled-out form instead of filling out a blank one repeatedly. You start with a template (prototype), make copies, then tweak the copies as needed.

How It Works

Instead of using constructors and builders every time, you:

  1. Create a fully-configured "prototype" object
  2. Clone it when you need a similar object
  3. Modify the clone's specific properties

This is especially useful when:

  • Object creation involves heavy computation
  • Objects share most configuration with slight variations
  • You need to avoid tight coupling to concrete classes

The Cloning Mechanism

The pattern relies on a clone() method that creates a copy of the object. There are two approaches:

  • Shallow copy: Copies the object's direct fields (references point to same nested objects)
  • Deep copy: Recursively copies the object and all nested objects (fully independent copies)

When to Use It

Use the Prototype Pattern when instantiation is more costly than copying, when you need many variations of similar objects, or when you want to avoid subclass explosion just to handle different configurations.

Key Takeaway: The Prototype Pattern creates new objects by cloning existing prototypes, optimizing performance and reducing complexity when object creation is expensive or when objects share similar configurations.