Java Design Pattern: Prototype

Prototype design pattern is used when very similar objects are frequently created. Prototype pattern clones objects and set the changed feature. In this way, less resources are consumed.

1. Prototype Pattern Class Diagram

prototype-pattern-class-diagram

2. Prototype Pattern Java Example

package designpatterns.prototype;
 
//prototype
interface Prototype {
    void setSize(int x);
    void printSize();
 }
 
// a concrete class
class A implements Prototype, Cloneable {
    private int size;
 
    public A(int x) {
        this.size = x;
    }
 
    @Override
    public void setSize(int x) {
        this.size = x;
    }
 
    @Override
    public void printSize() {
        System.out.println("Size: " + size);
    }
 
 
    @Override
    public A clone() throws CloneNotSupportedException {
        return (A) super.clone();
    }
}
 
//when we need a large number of similar objects
public class PrototypeTest {
    public static void main(String args[]) throws CloneNotSupportedException {
        A a = new A(1);
 
        for (int i = 2; i < 10; i++) {
            Prototype temp = a.clone();
            temp.setSize(i);
            temp.printSize();
        }
    }
}

3. Prototype Design Pattern Used in Java Standard Library

java.lang.Object - clone()

Category >> Design Patterns Stories  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. Nikolay Pasko on 2014-6-24

    You could also make clone() to accept “int size”, so that a newly cloned object would already have its size set upon return.
    Less code in caller methods. 🙂

  2. jeff on 2014-8-17

    sorry why less resources are consumed?

  3. ssdd on 2015-1-12

Leave a comment

*