原型模式

原型模式:用原型实例指定创建对象的类型,并通过拷贝这些原型创建对象

Java 语言中clone方法就是原型实例的案例 

    clone()  默认是浅拷贝 ,不会调用构造函数。直接通过内存的二进制流进行拷贝.

              clone无法深拷贝final 变量  , 两者无法共存  

  具体案例    (把)

import java.util.ArrayList;
import java.util.List;

public class Thing implements Cloneable {

    private ArrayList<String> params = new ArrayList<String>();

    public void setValue(String value) {
        params.add(value);
    }

    public List<String> getValues() {
        return params;
    }
    //默认浅拷贝
    @Override
    public Thing clone(){

        Thing thing = null;
        try {
            thing = (Thing) super.clone();
            //深拷贝 注释下面一行表示浅拷贝, 如果变量是final型 只能赋值一次 会报错  无法共存
            thing.params = (ArrayList<String>) this.params.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return thing;
    }


    public static void main(String... args) {

        Thing thing = new Thing();
        thing.setValue("张三");
        Thing clonet = thing.clone();
        clonet.setValue("李四");
        System.out.println(thing.params);
    }
}

通过自定义二进制流来实现深拷贝

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Thing implements Serializable {//实现序列化接口

    private final  ArrayList<String> params = new ArrayList<String>();

    public void setValue(String value) {
        params.add(value);
    }

    public List<String> getValues() {
        return params;
    }
//    //默认浅拷贝
//    @Override
//    public Thing clone(){
//
//        Thing thing = null;
//        try {
//            thing = (Thing) super.clone();
//            //深拷贝
////            thing.params = (ArrayList<String>) this.params.clone();
//        } catch (CloneNotSupportedException e) {
//            e.printStackTrace();
//        }
//        return thing;
//    }


    public static void main(String... args) throws IOException, ClassNotFoundException {

//        Thing thing = new Thing();
//        thing.setValue("张三");
//        Thing clonet = thing.clone();
//        clonet.setValue("李四");
//        System.out.println(thing.params);
        Thing thing = new Thing();
        thing.setValue("张三");
        Thing depthclone = (Thing) depthClone(thing);
        depthclone.setValue("李四");
        System.out.println(depthclone.params);
        System.out.println(thing.params);
    }

    //通过自定义二进制流来操作对象,从而实现深拷贝
    public static Object depthClone(Object srcobj) throws IOException, ClassNotFoundException {
        Object cloneobj = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(srcobj);

        ByteArrayInputStream in = new ByteArrayInputStream(outputStream.toByteArray());
        ObjectInputStream oi = new ObjectInputStream(in);
        cloneobj=oi.readObject();
        return cloneobj;
    }

}
原文地址:https://www.cnblogs.com/09120912zhang/p/9110774.html