Prototype原型模式

原型模式就是以一個對象做爲原型構建另外一個對象,也就是咱們說的克隆。java

 

克隆作法是什麼呢?ide

  對象實現克隆接口Clonable接口,將訪問方法clone重寫,訪問權限變大。ui

 

默認的克隆是淺拷貝,指的是外層對象是new的,可是對象的屬性都是經過值copy給的的,也就會出現一個問題,引用數據類型用的都是同一個對象this

深拷貝的作法:spa

   重寫clone方法,針對每個引用數據類型new 一個對象,只是將基本數據類型的值放入進去該對象prototype

  或者能夠利用序列化作媒介完成,深拷貝。code

 

代碼:對象

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
相關文章
相關標籤/搜索