原型模式

Prototype

原型模式是一种创建型设计模式,它通过复制一个已经存在的实例来返回新的实例,而不是新建实例.被复制的实例就是我们所称的原型,这个原型是可定制的.
原型模式多用于创建复杂的或者耗时的实例, 因为这种情况下,复制一个已经存在的实例可以使程序运行更高效,或者创建值相同但名字不同的同类数据。

原型模式的主要思想是基于现有的对象克隆一个新的对象出来,一般是有对象的内部提供克隆的方法,通过该方法返回一个对象的副本。

这种创建对象的方式,相比其他创建型模式不同,

之前的讲述的工厂模式与抽象工厂都是通过工厂封装具体的new操作的过程,返回一个新的对象.

示例:

public interface Prototype{
    Object cloneme();
}

---

//实现了克隆方法的原型类
public class PrototypeClass implements Cloneable,Serializable, Prototype{

    private static final long serialVersionUID = 1L;

    String name;

    int age;

    List list;

    Date time;

    PrototypeClass(String name, int age, List list){
        this.name = name;
        this.age = age;
        this.list = list;
        this.time = new Date();
    }

    public void show(){
        Q.p(this.name + " " + this.age + " " + this.time + " " + this.list + " " + this.hashCode());
    }

    @Override
    public PrototypeClass cloneme(){
        PrototypeClass that = null;
        try {
            // 将对象写到流里
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            // 从流里读回来
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            that = (PrototypeClass) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            System.out.println(e);
        }
        return that;
    }

}

---

//测试类
public class ProtoTypeTest{
    public static void main(String[] args){
        List<String> list = new ArrayList<>();
        list.add("123");
        list.add("abc");

        PrototypeClass pc = new PrototypeClass("name1", 10, list);
        pc.show();

        PrototypeClass clone = (PrototypeClass) pc.cloneme();
        clone.show();
    }
}

---

输出:

name1 10 Sun Mar 12 16:18:11 CST 2017 [123, abc] 1531448569
name1 10 Sun Mar 12 16:18:11 CST 2017 [123, abc] 1530388690

可见拷贝的两个对象中的属性完全相同,但hashCode不同.

end




原文地址:https://www.cnblogs.com/luangeng/p/6538244.html