原型模式(Prototype)

2017-08-16  本文已影响0人  bobcorbett

原型模式(Prototype),用原型实例制定创建对象的种类,并且通过拷贝这些原型创建新的对象。
原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需知道任何创建的细节。

主方法

public class main {
    public static void main(String[] args) {
        ConcretePrototype1 p1 = new ConcretePrototype1("I");
        ConcretePrototype1 c1 = (ConcretePrototype1)p1.Clone();//从父类强转为子类
        System.out.println("Clone: {" + c1.getId() + "}");
    }
}

原型类

public abstract class Prototype {
    private String id;

    public Prototype(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }

    public abstract Prototype Clone();
}

具体原型实现类1,可以写23456789.....

public class ConcretePrototype1 extends Prototype {
    public ConcretePrototype1(String id) {
        super(id);
    }

    public Prototype Clone() {
        Prototype prototype = new ConcretePrototype1(super.getId());
        return prototype;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读