1.意圖
用原型實(shí)例指定創(chuàng)建對(duì)象的種類伏蚊,并且通過(guò)拷貝這些原型創(chuàng)建新的對(duì)象沸手。
2.結(jié)構(gòu)圖和代碼
它的結(jié)構(gòu)圖非常簡(jiǎn)單味廊,我們以Intent為例子:
Intent的clone方法非常簡(jiǎn)單:
@Override
public Object clone() {
return new Intent(this);
}
返回一個(gè)新的Intent對(duì)象纲堵。
克隆操作分深拷貝和淺拷貝却嗡,淺拷貝說(shuō)白了就是把原對(duì)象所有的值和引用直接賦給新對(duì)象。深拷貝則不僅把原對(duì)象的值賦給新對(duì)象翻诉,而且會(huì)把原對(duì)象的引用對(duì)象也重新創(chuàng)建一遍再賦給新對(duì)象炮姨。
我們具體分析一下Intent是淺拷貝還是深拷貝吧:
public Intent(Intent o) {
this.mAction = o.mAction;
this.mData = o.mData;
this.mType = o.mType;
this.mPackage = o.mPackage;
this.mComponent = o.mComponent;
this.mFlags = o.mFlags;
//下面幾個(gè)是引用對(duì)象被重新創(chuàng)建了,是深拷貝
if (o.mCategories != null) {
this.mCategories = new HashSet<String>(o.mCategories);
}
if (o.mExtras != null) {
this.mExtras = new Bundle(o.mExtras);
}
if (o.mSourceBounds != null) {
this.mSourceBounds = new Rect(o.mSourceBounds);
}
}
這里我們?yōu)槭裁碔ntent要重寫(xiě)Object的clone方法碰煌,就與深拷貝有關(guān)舒岸。
其實(shí)我們查看Object的clone()方法源碼和注釋,默認(rèn)的super.clone()用的就是淺拷貝:
/**
* Creates and returns a copy of this {@code Object}. The default
* implementation returns a so-called "shallow" copy: It creates a new
* instance of the same class and then copies the field values (including
* object references) from this instance to the new instance. A "deep" copy,
* in contrast, would also recursively clone nested objects. A subclass that
* needs to implement this kind of cloning should call {@code super.clone()}
* to create the new instance and then create deep copies of the nested,
* mutable objects.
*/
protected Object clone() throws CloneNotSupportedException {
if (!(this instanceof Cloneable)) {
throw new CloneNotSupportedException("Class doesn't implement Cloneable");
}
return internalClone((Cloneable) this);
}
這種形式屬于簡(jiǎn)單形式的原型模式芦圾,如果需要?jiǎng)?chuàng)建的原型數(shù)目不固定蛾派,可以創(chuàng)建一個(gè)原型管理器,在復(fù)制原型對(duì)象之前个少,客戶端先在原型管理器中查看
是否存在滿足條件的原型對(duì)象洪乍,如果有,則直接使用夜焦,如果沒(méi)有壳澳,克隆一個(gè),這種稱作登記形式的原型模式茫经。
適用原型模式可以對(duì)客戶隱藏產(chǎn)品的具體類巷波,因此減少了客戶知道的名字的數(shù)目萎津,此外是客戶無(wú)需改變
原型模式的缺陷是每個(gè)原型的子類都必須實(shí)現(xiàn)Cloneable接口,這個(gè)實(shí)現(xiàn)起來(lái)有時(shí)候比較困難抹镊。
3. 效果
(1).創(chuàng)建型模式
(2).運(yùn)行時(shí)刻增加和刪除產(chǎn)品
(3).改變只以指定新對(duì)象(ctrl+v姜性,然后修改)
(4).改變結(jié)構(gòu)以指定新對(duì)象。(類似2髓考,實(shí)現(xiàn)不同而已)
(5).減少子類的構(gòu)造