原型设计模式——深浅克隆


一. 简介

通过原型实例复制出一个内容一致的新对象,所谓内容一致指类中的基本类型与引用类型一致,通过这一点区分了原型模式深浅克隆

  • 浅克隆:复制后的对象只有基本类型值一致,引用类仅复制了原型的引用地址,但是指向的对象实际上是一个,改变原型对象的引用类型后,复制对象的引用类型随即也改变;

  • 深克隆:复制后的对象基本类型值一致,引用类型地址与原型引用类型地址不同,也就是引用类型同时也被复制出一份并将地址赋于复制后的引用类型属性


二. 试用场景

  • new产生的一个对象需要非常繁琐的过程(数据准备、访问权限等)
  • 构造函数比较复杂
  • 循环体中生产大量对象时

三.代码示例

  • 通过序列化与反序列化实现深克隆,所以将被克隆的对象和对象中的引用类型都要实现Serializable序列化接口(注:如使用其他序列化请随即改变实现接口类型)
  • 实现Cloneable接口,此接口不包含任何方法!仅仅是用来指示Object类中clone()方法可以用来合法的进行克隆。如果在没有实现Cloneable接口的实例上调用Object的clone()方法,则会导致抛出CloneNotSupporteddException;(注:Object的clone()为浅克隆),我们重写Object的clone()方法使其调用我们深克隆方法

*此例子仅供测试,请误纠结是否符合显示逻辑

1. 头部类

此类中定义了头发的整体颜色,发型,与头发集合,提供了深克隆方法deepClone()与浅克隆方法shallowClone(),重写了Object的clone(),使其调用deepClone()返回深克隆对象

public class Head implements Cloneable, Serializable {
    //整体颜色
    private String color;
    //发型
    private String shape;
    //头发集合
    private List<Hair> hairList;

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getShape() {
        return shape;
    }

    public void setShape(String shape) {
        this.shape = shape;
    }

    public List<Hair> getHairList() {
        return hairList;
    }

    public void setHairList(List<Hair> hairList) {
        this.hairList = hairList;
    }

    /**
     * 重写Object的克隆是浅克隆,我们重写使其调用我们的深克隆方法
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return deepClone();
    }

    /**
     * 深克隆
     */
    public Head 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);
            Head copy = (Head)ois.readObject();
            return copy;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 浅克隆
     */
    public Head shallowClone(){
        Head headClone = new Head();
        headClone.setColor(this.getColor());
        headClone.setShape(this.shape);
        headClone.setHairList(this.hairList);
        return headClone;
    }

    @Override
    public String toString() {
        return "Head{" +
                "color='" + color + '\'' +
                ", shape='" + shape + '\'' +
                ", hairList=" + hairList +
                '}';
    }
}
2. 头发类

头发类定义了单根头发的颜色和长度


public class Hair implements Serializable {
    private String color;
    private long  length;

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public long getLength() {
        return length;
    }

    public void setLength(long length) {
        this.length = length;
    }

}

3. 测试方法

测试通过调用深克隆与克隆方法,对比原型与复制类中的基本类型与引用类型是否一致

public class Run {

    public static void main(String[] args) throws CloneNotSupportedException {
        Head head = new Head();
        head.setColor("黑色");
        head.setShape("渣男锡纸烫");
        List hairList = new ArrayList();
        for (int i=1 ;i<=100 ; i++){
            Hair hair = new Hair();
            hair.setColor("黑色");
            hair.setLength(10);
            hairList.add(hair);
        }
        head.setHairList(hairList);

        shallowCloneTest(head);
        deepcloneTest(head);
    }

    private static void deepcloneTest(Head head) throws CloneNotSupportedException {
        Head cloneHead = (Head) head.clone();
        System.out.println("---------------深克隆测试---------------------");
        System.out.println("Head对象对比:"+ (head == cloneHead));
        System.out.println("Head中属性HairList对比:"+ (head.getHairList() == cloneHead.getHairList()));
        System.out.println(head.toString());
        System.out.println(cloneHead.toString());
    }

    private static void shallowCloneTest(Head head) throws CloneNotSupportedException {
        Head cloneHead = head.shallowClone();
        System.out.println("---------------浅克隆测试---------------------");
        System.out.println("Head对象对比:"+ (head == cloneHead));
        System.out.println("Head中属性HairList对比:"+ (head.getHairList() == cloneHead.getHairList()));
        System.out.println(head.toString());
        System.out.println(cloneHead.toString());
    }
}
4. 测试结果

从测试结果发现,浅克隆只有基本类型值一致,但引用类型地址是一样的;而深克隆不仅基本类型值一致,引用类型地址也各不相同,这就说明深克隆通过原型完整的复制新对象

---------------浅克隆测试---------------------
Head对象对比:false
Head中属性HairList对比:true
Head{color='黑色', shape='渣男锡纸烫', hairList=[com.mao.prototype.Hair@7f787395, com.mao.prototype.Hair@3cec7c94, com.mao.prototype.Hair@49e6f7cb]}
Head{color='黑色', shape='渣男锡纸烫', hairList=[com.mao.prototype.Hair@7f787395, com.mao.prototype.Hair@3cec7c94, com.mao.prototype.Hair@49e6f7cb]}
---------------深克隆测试---------------------
Head对象对比:false
Head中属性HairList对比:false
Head{color='黑色', shape='渣男锡纸烫', hairList=[com.mao.prototype.Hair@7f787395, com.mao.prototype.Hair@3cec7c94, com.mao.prototype.Hair@49e6f7cb]}
Head{color='黑色', shape='渣男锡纸烫', hairList=[com.mao.prototype.Hair@458db581, com.mao.prototype.Hair@5a874bd3, com.mao.prototype.Hair@68833813]}