Android設(shè)計(jì)模式系列(10)--SDK源碼之原型模式

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要重寫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)造

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容