Design Patterns Handbook
  • Introduction
  • Creational Patterns
    • Builder
    • Factory
    • Abstract Factory
    • Factory Method
    • Prototype
    • Singleton
    • Object Pool
    • Revealing Constructor
  • Structural Patterns
    • Adapter
    • Composite
    • Proxy
    • Flyweight
    • Facade
    • Bridge
    • Decorator
    • Private Class Data
  • Behavioral Patterns
    • Template Method
    • Mediator
    • Chain Of Responsibility
    • Observer
    • Strategy
    • Command
    • State
    • Visitor
    • Memento
    • Interpreter
    • Null Object
    • Iterator
    • Middleware
  • Clean Code Patterns
    • Extract Method
    • Clarify Responsibility
    • Remove Duplications
    • Keep Refactoring
    • Always Unit Test
    • Create Data Type
    • Comment to Better Name
    • Consistent Naming
    • If-else over ternary operator
    • Composition over Inheritance
    • Too Many Returns
    • Private to Interface
  • Anti Patterns
    • Big Ball of Mud
    • Singleton
    • Mad Scientist
    • Spaghetti Code
    • It Will Never Happen
    • Error Codes
    • Commented Code
    • Abbreviations
    • Prefixes
    • Over Patternized
    • Generic Interface over Function
Powered by GitBook
On this page
  • Example - Simple Prototype
  • Example - Define own prototype interface

Was this helpful?

  1. Creational Patterns

Prototype

Prototype design pattern suggest to create a clone of a prototype rather than using new keyword and deep-copy all values to a clonned instance.

Example - Simple Prototype

In order to implement prototype patern, we can simply implement Clonable interface from Java.

class HumanCell implements Cloneable {

    private String dna;

    public HumanCell(String dna) {
        this.dna = dna;
    }

    public String getDna() {
        return dna;
    }

    // all complex objects must be recreated (lists, maps, POJOs)
    public Object clone() throws CloneNotSupportedException {
        return new HumanCell(dna);
    }
}

Then we can clone human cells like this.

HumanCell cell = new HumanCell("DNA123");
HumanCell identical = (HumanCell) cell.clone();

Example - Define own prototype interface

We can create our own interface that will define how a prototype should be copied into a new class.

interface Cell {
    Cell split();
    String getDna();
}

class SingleCellOrganism implements Cell {

    private String dna;

    public SingleCellOrganism(String dna) {
        this.dna = dna;
    }

    public String getDna() {
        return dna;
    }

    // all complex objects must be recreated (lists, maps, POJOs)
    public Cell split() {
        return new SingleCellOrganism(dna);
    }
}

Then we can use it as follows and we can exclude casting Object into a specific type.

Cell cell = new SingleCellOrganism("DNA123");
Cell identical = i1.split();
PreviousFactory MethodNextSingleton

Last updated 5 years ago

Was this helpful?