设计模式之原型模式

第一种克隆模式(浅克隆)

/**
 * @作者 five-five
 * @创建时间 2020/8/6
 */
public class Demo01 implements Cloneable{
    private int id=0;
    private String student="123132";

    public void setId(int id) {
        this.id = id;
    }

    public void setStudent(String student) {
        this.student = student;
    }

    public int getId() {
        return id;
    }

    public String getStudent() {
        return student;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        //都是基本类型直接使用默认的clone方法即可
        return super.clone();
    }
}

2.深克隆模式

import java.io.*;

/**
 * @作者 five-five
 * @创建时间 2020/8/6
 */
public class Demo02 implements Serializable, Cloneable {
    private int id=11;
    private String name="1231321";
    private Demo01 demo01=new Demo01();

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setDemo01(Demo01 demo01) {
        this.demo01 = demo01;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Demo01 getDemo01() {
        return demo01;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        //第一种方式(比较死板)
        Object obj = null;
        obj = super.clone();
        Demo02 demo02 = (Demo02) obj;
        //对引用类型的单独处理
        demo02.demo01 = (Demo01) demo01.clone();
        return obj;
    }

    /**
     * <p>使用IO的方式克隆</p>
     *
     * @return
     */
    public Object deepProtoCloneByIO() {
        //创建流对象
        ByteArrayInputStream bis = null;
        ByteArrayOutputStream bos = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);//当前这个对象以对象流的方式输出
            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            Demo02 o = (Demo02) ois.readObject();

            return o;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

测试代码:

/**
 * @作者 five-five
 * @创建时间 2020/8/6
 */
public class Client {
    public static void main(String[] args) throws Exception {
        Demo01 demo01=new Demo01();
        Demo02 demo02=new Demo02();
        Object clone = demo01.clone();
        Demo02 clone1 = (Demo02)demo02.clone();
        System.out.println(demo01.hashCode());
        System.out.println(demo02.hashCode());
        System.out.println(demo02.getDemo01().hashCode());
        System.out.println(clone.hashCode());
        System.out.println(clone1.getDemo01().hashCode());
    }
}

测试结果如图:

原文地址:https://www.cnblogs.com/five-five/p/13447743.html