原型模式

31 阅读1分钟

1.原型模式介绍

原型模式(Prototype Design Pattern),将已经创建的对象作为原型,通过原型模式创建出相同的对象。

对于一些通过复杂计算得到的对象,或者是一些较大的对象等(对象获取的成本高),可以通过原型模式获取,而不是每次都比较费工夫的去重新构建对象。

2.深克隆与浅克隆

  1. 浅克隆:复制对象的值与原对象相同,对象的引用指向原对象的地址。

public class Person implements Cloneable {


    @Override
    public Person clone() {
        try {
            Person clone = (Person) super.clone();
            return clone;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }

}

@Test
public void test() {
    Person person = new Person();
    Person clone = person.clone();

    System.out.println(man==man1);
}
  1. 深克隆:复制的对象引用类型也是新的值
public class Person implements Cloneable ,Serializable{


    @Override
    public Person clone() {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(this);

            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            return (Person) ois.readObject();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }


}
@Test
public void test() {
    Person person = new Person();
    Person clone = person.clone();
    System.out.println(clone==person);
}