23种设计模式之原型模式

原型模式(Prototype):用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

package designMode.prototype;

abstract class Prototype{
    
    private String id;
    
    public Prototype(String id) {
        this.id = id;
    }
    public abstract Prototype copy();
    
    public String getId() {
        return id;
    }
}
package designMode.prototype;

class ConcretePrototype extends Prototype implements Cloneable{

    public ConcretePrototype(String id) {
        super(id);
    }

    @Override
    public Prototype copy() {
        Prototype p = null;
        try {
            p = (Prototype) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return p;
    }

}
package designMode.prototype;

class Test {
    public static void main(String[] args) {
        ConcretePrototype p = new ConcretePrototype("1");
        ConcretePrototype temp = (ConcretePrototype) p.copy();
        System.out.println(temp.getId());
    }
}

 

posted @ 2017-08-11 14:01  如果屈原会编程  阅读(134)  评论(0编辑  收藏  举报