原型模式

一、啥是原型模式?

   把对象中配置的依赖关系,在每次使用对象之前,都会创建一个新的对象,并且将依赖关系完整的赋值给这个新创建的对象。
   如:spring beacon中的scope="prototype";

二、深克隆、浅克隆

   浅克隆:不只是克隆了相同的属性值,还克隆了引用地址;

   深克隆:单纯的克隆相同的属性值,不克隆引用地址;

三、demo

被克隆类:

/**
 * @ather: lucksheep
 * @date: 2018/8/10 17:21
 * @description:
 */
public class BaseClone implements Serializable {

    private String tall;

    public String getTall() {
        return tall;
    }

    public void setTall(String tall) {
        this.tall = tall;
    }
}

克隆类:

import lombok.Data;

import java.io.*;

/**
 * @ather: lucksheep
 * @date: 2018/8/10 16:48
 * @description:
 */
@Data
public class Prototype implements Cloneable ,Serializable{

    public String name;

    public BaseClone baseClone;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public Object deepClone(){
        try {
            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            ByteArrayInputStream bis=new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois =new ObjectInputStream(bis);

            Prototype pro=(Prototype) ois.readObject();
            return pro;

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

测试:

/**
 * @ather: lucksheep
 * @date: 2018/8/10 16:49
 * @description:
 */
public class Test {

    public static void main(String[] args) {

        Prototype p = new Prototype();
        p.setName("zhangsan");

        BaseClone baseClone=new BaseClone();
        baseClone.setTall("我是你爸爸!");
        p.setBaseClone(baseClone);

        System.out.println(p.getBaseClone().getTall()+"  "+p.getBaseClone());
        try {
            Prototype p2=(Prototype) p.clone();
            System.out.println(p2.getBaseClone().getTall()+"  "+p2.getBaseClone());

            Prototype p3=(Prototype) p.deepClone();
            System.out.println(p3.getBaseClone().getTall()+"  "+p3.getBaseClone());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

测试结果:

我是你爸爸!  com.demo.prototype.BaseClone@140e19d
我是你爸爸!  com.demo.prototype.BaseClone@140e19d
我是你爸爸!  com.demo.prototype.BaseClone@1d6c5e0

Process finished with exit code 0
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容