设计模式-原型模式

106 阅读1分钟

1,原型模式浅克隆的问题:

@Data
public class ConcretePrototype implements Cloneable {
    private int age;
    private String name;
    private List<String> hobbies;
    @Override
    public ConcretePrototype clone() {
        try {
            return (ConcretePrototype)super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            return null;
        }
    }
}

接下来需要深克隆:

public ConcretePrototype 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);
            
            return (ConcretePrototype)ois.readObject();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
克隆是默认是浅克隆,是新创建了一个对象,里面的基本类型都是新对象的,但是如果是引用类型变量则是用的原对象的引用类型变量的地址。
基本类型:
①整数类型:`longintshortbyte`  
②[浮点]:`floatdouble`  
③字符类型:`char`  
④[布尔]:`boolean`
引用类型:
类、 接口类型、 数组类型、 枚举类型、 注解类型、 字符串型
例如,`String`类型就是引用类型。  
简单来说,所有的非基本数据类型都是引用数据类型。

注意原型模式和单利模式是冲突的,互斥的,一个类不能既做单例,又实现Cloneable接口。

凡是实现Cloneable接口的都是浅克隆。
怎么样做才能实现深克隆:
1),序列化
2),转Json