日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Prototype模式

發布時間:2024/7/19 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Prototype模式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原型模式創建對象不調用原對象的構造函數,是直接copy原對象的
淺克隆:對值類型的成員變量進行值的復制,對引用類型的成員變量只復制引用,不復制引用的對象.
深克隆:對值類型的成員變量進行值的復制,對引用類型的成員變量也進行引用對象的復制.
/**
* Created by marcopan on 17/10/20.
*/
public class Prototype implements Cloneable {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
} /**
* Created by marcopan on 17/10/20.
*/
public class NewPrototype implements Cloneable {
private String id;
private Prototype prototype;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public Prototype getPrototype() {
return prototype;
}

public void setPrototype(Prototype prototype) {
this.prototype = prototype;
}

public Object clone() {
NewPrototype ret = null;
try {
ret = (NewPrototype)super.clone();
ret.prototype = (Prototype)this.prototype.clone();
return ret;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}

public static void main(String[] args) {
Prototype pro = new Prototype();
pro.setName("original object");
NewPrototype newObj = new NewPrototype();
newObj.setId("test1");
newObj.setPrototype(pro);

NewPrototype clonObj = (NewPrototype)newObj.clone();
clonObj.setId("testClone");
clonObj.getPrototype().setName("changed object");

System.out.println("original object id:" + newObj.getId());
System.out.println("original object name:" + newObj.getPrototype().getName());

System.out.println("cloned object id:" + clonObj.getId());
System.out.println("cloned object name:" + clonObj.getPrototype().getName());
}
}
運行結果:

original object id:test1
original object name:original object
cloned object id:testClone
cloned object name:changed object



轉載于:https://www.cnblogs.com/panning/p/7701136.html

總結

以上是生活随笔為你收集整理的Prototype模式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。