Prototype design pattern

The prototype design pattern allows you to create an object by copying properties from the prototype object.

problems

Suppose class has many properties. But instances in your application have slightly different each from other. For every an object creation you need write boilerplate code. It can be resolved by creation one the pre-configure object - prototype object.

Suppose class has property that stores expensive data, for example downloaded from internet or database. And instances use same data. Then good idea is load data only for first object and share it for other.

advantages

  1. Remove boilerplate code.
  2. Save resources.
public class Demo implements Cloneable  {

    private List<String> expensiveData;

    public Demo(){
        expensiveData = new ArrayList<>();
    }

    public Demo(List<String> argExpensiveData){
        expensiveData = argExpensiveData;
    }

    @Override
    protected Demo clone() throws CloneNotSupportedException {
        Demo c = new Demo();
        c.expensiveData.addAll(expensiveData);
        return c;
    }
}
public class Demo implements Cloneable { private int prop1; private int propN; public Demo(){ } @Override protected Demo clone() throws CloneNotSupportedException { return (Demo)super.clone(); } public static void main(String[] args) throws CloneNotSupportedException { Demo prototype = new Demo(); prototype.prop1 = 10; prototype.propN = 100; Demo c = prototype.clone(); // result will be "prop1=10 propN=100" System.out.println("prop1="+c.prop1+" propN="+c.propN); } }