Prototype原型模式

原型模式就是以一个对象作为原型构建另一个对象,也就是我们说的克隆。

 

克隆做法是什么呢?

  对象实现克隆接口Clonable接口,将访问方法clone重写,访问权限变大。

 

默认的克隆是浅拷贝,指的是外层对象是new的,但是对象的属性都是通过值copy给的的,也就会出现一个问题,引用数据类型用的都是同一个对象

深拷贝的做法:

   重写clone方法,针对每一个引用数据类型new 一个对象,只是将基本数据类型的值放入进去该对象

  或者可以利用序列化做媒介完成,深拷贝。

 

代码:

package com.zhen.build_template.prototype;

import java.io.*;

/**
 * @author zhen
 * @Date 2019/5/28 21:48
 */
public class Prototype implements Cloneable, Serializable{
    public String name = "嘻嘻";
    public C c = new C("张三", 2);
    @Override
    public Object clone() throws CloneNotSupportedException {
        Prototype prototype =  (Prototype) super.clone();
        return prototype;
    }

    public Object deepClone() throws IOException, ClassNotFoundException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);

        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        Object obj = ois.readObject();
        return obj;

    }

    public Object deepClone1()  throws CloneNotSupportedException{
        Prototype object = (Prototype) super.clone();
        object.c = new C(this.c.name, this.c.age);
        return object;
    }

}

class C implements Serializable{
    public String name;
    public int age;
    public C(String name, int age){
        this.age = age;
        this.name = name;
    }
}


package com.zhen.build_template.prototype;

/**
 * @author zhen
 * @Date 2019/5/28 21:50
 */
public class TestClone {
    public static void main(String[] args) throws Exception{
        Prototype prototype = new Prototype();
        Prototype prototype1 = (Prototype) prototype.clone();
        System.out.println(prototype.equals(prototype1));
        System.out.println(prototype.name.equals(prototype1.name));
        System.out.println(prototype.c.equals(prototype1.c));

        Prototype prototype2 = (Prototype) prototype.deepClone();
        System.out.println(prototype.equals(prototype2));
        System.out.println(prototype.name==prototype2.name);
        System.out.println(prototype.c.equals(prototype2.c));
        System.out.println(prototype.c.name==prototype2.c.name);
    }
}
View Code

 

posted @ 2019-05-29 11:27  guodaxia  阅读(135)  评论(0编辑  收藏  举报