Android設(shè)計(jì)模式系列--原型模式
CV一族,應(yīng)該很容易理解原型模式的原理,復(fù)制,粘貼完后看具體情況是否修改,其實(shí)這就是原型模式。
從java的角度看,一般使用原型模式有個(gè)明顯的特點(diǎn),就是實(shí)現(xiàn)cloneable的clone()方法。
原型模式,能快速克隆出一個(gè)與已經(jīng)存在對(duì)象類似的另外一個(gè)我們想要的新對(duì)象。
1.意圖
用原型實(shí)例指定創(chuàng)建對(duì)象的種類,并且通過拷貝這些原型創(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ì)象。
克隆操作分深拷貝和淺拷貝,淺拷貝說白了就是把原對(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ì)象,如果有,則直接使用,如果沒有,克隆一個(gè),這種稱作登記形式的原型模式。
適用原型模式可以對(duì)客戶隱藏產(chǎn)品的具體類,因此減少了客戶知道的名字的數(shù)目,此外是客戶無需改變
原型模式的缺陷是每個(gè)原型的子類都必須實(shí)現(xiàn)Cloneable接口,這個(gè)實(shí)現(xiàn)起來有時(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)造