# 原型模式

# 简介

创建型模式,通过克隆创建新对象。根据业务需要实现对应的拷贝方式:浅拷贝、深拷贝。

# 示例

public class Prototype implements Cloneable, Serializable {
    private String name;
    private String[] things = {"A", "B", "C"};

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

    public void doSomeThing() {
        System.out.println(String.format("%s,do some things: %s, %s, %s", this.name, things[0], things[1], things[2]));
    }

    /**
     * 浅拷贝
     *
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    public Prototype clone() throws CloneNotSupportedException {
        return (Prototype) super.clone();
    }

    /**
     * 深拷贝
     *
     * @return
     */
    public Prototype deepClone() throws IOException, ClassNotFoundException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(this);

        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bais);
        Prototype prototype = (Prototype) ois.readObject();
        return prototype;
    }

    public String[] getThings() {
        return things;
    }
}

# 调用

@Test
public void tt() throws CloneNotSupportedException, IOException, ClassNotFoundException {
    Prototype p1 = new Prototype("张三");

    Prototype p2 = p1.clone();
    System.out.println(p1.getThings() == p2.getThings());

    Prototype p3 = p1.deepClone();
    System.out.println(p1.getThings() == p3.getThings());
}