Prototype Design Pattern

Back To Index

Overview

The Prototype Design Pattern is used to create duplicate objects while ensuring performance. It allows for cloning objects, which is particularly useful when object creation is expensive or complex.

Key Characteristics

Implementation

The following is an example of a Prototype implementation in Java:


interface Prototype {
    Prototype clone();
}

class ConcretePrototype implements Prototype {
    private String data;

    public ConcretePrototype(String data) {
        this.data = data;
    }

    public String getData() {
        return data;
    }

    @Override
    public Prototype clone() {
        return new ConcretePrototype(this.data);
    }

    @Override
    public String toString() {
        return "ConcretePrototype{data='" + data + "'}";
    }
}

public class PrototypeDemo {
    public static void main(String[] args) {
        ConcretePrototype prototype = new ConcretePrototype("Initial Data");
        ConcretePrototype clonedPrototype = (ConcretePrototype) prototype.clone();

        System.out.println(prototype);
        System.out.println(clonedPrototype);
    }
}
    

When to Use

Advantages

Disadvantages

Back To Index