Design Pattern: Prototype

Prototype Pattern là một trong những pattern thuộc Creational Patterns (Abstract Factory, Builder, Factory Method, Prototype, Singleton)

Mục đích của Prototype patern là Clone.

/**
 * Prototype class
 */
interface Prototype {
    void setX(int x);

    void printX();

    int getX();
}

/**
 * Implementation of prototype class
 */
class PrototypeImpl implements Prototype, Cloneable {
    private int x;

    /**
     * Constructor
     */
    public PrototypeImpl(int x) {
        setX(x);
    }

    @Override
    public void setX(int x) {
        this.x = x;
    }

    @Override
    public void printX() {
        System.out.println("Value: " + x);
    }

    @Override
    public int getX() {
        return x;
    }

    @Override
    public PrototypeImpl clone() throws CloneNotSupportedException {
        return (PrototypeImpl) super.clone();
    }
}

/**
 * Client code
 */
public class PrototypeTest {
    public static void main(String args[]) throws CloneNotSupportedException {
        PrototypeImpl prototype = new PrototypeImpl(1000);

        for (int y = 1; y < 10; y++) {
            // Create a defensive copy of the object to allow safe mutation
            Prototype tempotype = prototype.clone();

            // Derive a new value from the prototype's "x" value
            tempotype.setX(tempotype.getX() * y);
            tempotype.printX();
        }
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s