设计模式专家

spring 设计模式篇—原型模式

2018-08-10  本文已影响58人  Lucksheep

一、啥是原型模式?

   把对象中配置的依赖关系,在每次使用对象之前,都会创建一个新的对象,并且将依赖关系完整的赋值给这个新创建的对象。
   如: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
上一篇 下一篇

猜你喜欢

热点阅读