日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產(chǎn)品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Android設計模式系列--原型模式

CV一族,應該很容易理解原型模式的原理,復制,粘貼完后看具體情況是否修改,其實這就是原型模式。
從java的角度看,一般使用原型模式有個明顯的特點,就是實現(xiàn)cloneable的clone()方法。
原型模式,能快速克隆出一個與已經(jīng)存在對象類似的另外一個我們想要的新對象。

1.意圖
用原型實例指定創(chuàng)建對象的種類,并且通過拷貝這些原型創(chuàng)建新的對象。
熱門詞匯:克隆 深拷貝 淺拷貝

2.結構圖和代碼
它的結構圖非常簡單,我們以Intent為例子:

Intent的clone方法非常簡單:

 
 
 
  1. @Override 
  2. public Object clone() {  
  3.     return new Intent(this);  
  4. }  

返回一個新的Intent對象。
克隆操作分深拷貝和淺拷貝,淺拷貝說白了就是把原對象所有的值和引用直接賦給新對象。深拷貝則不僅把原對象的值賦給新對象,而且會把原對象的引用對象也重新創(chuàng)建一遍再賦給新對象。
我們具體分析一下Intent是淺拷貝還是深拷貝吧:

 
 
 
  1. public Intent(Intent o) {  
  2.     this.mAction = o.mAction;  
  3.     this.mData = o.mData;  
  4.     this.mType = o.mType;  
  5.     this.mPackage = o.mPackage;  
  6.     this.mComponent = o.mComponent;  
  7.     this.mFlags = o.mFlags;  
  8.     //下面幾個是引用對象被重新創(chuàng)建了,是深拷貝  
  9.     if (o.mCategories != null) {  
  10.         this.mCategories = new HashSet(o.mCategories);  
  11.     }  
  12.     if (o.mExtras != null) {  
  13.         this.mExtras = new Bundle(o.mExtras);  
  14.     }  
  15.     if (o.mSourceBounds != null) {  
  16.         this.mSourceBounds = new Rect(o.mSourceBounds);  
  17.     }  
  18. }  

這里我們?yōu)槭裁碔ntent要重寫Object的clone方法,就與深拷貝有關。
其實我們查看Object的clone()方法源碼和注釋,默認的super.clone()用的就是淺拷貝:

 
 
 
  1. /**  
  2.  * Creates and returns a copy of this {@code Object}. The default  
  3.  * implementation returns a so-called "shallow" copy: It creates a new  
  4.  * instance of the same class and then copies the field values (including  
  5.  * object references) from this instance to the new instance. A "deep" copy,  
  6.  * in contrast, would also recursively clone nested objects. A subclass that  
  7.  * needs to implement this kind of cloning should call {@code super.clone()}  
  8.  * to create the new instance and then create deep copies of the nested,  
  9.  * mutable objects.  
  10.  */ 
  11. protected Object clone() throws CloneNotSupportedException {  
  12.     if (!(this instanceof Cloneable)) {  
  13.         throw new CloneNotSupportedException("Class doesn't implement Cloneable");  
  14.     }  
  15.   
  16.     return internalClone((Cloneable) this);  
  17. }  

這種形式屬于簡單形式的原型模式,如果需要創(chuàng)建的原型數(shù)目不固定,可以創(chuàng)建一個原型管理器,在復制原型對象之前,客戶端先在原型管理器中查看
是否存在滿足條件的原型對象,如果有,則直接使用,如果沒有,克隆一個,這種稱作登記形式的原型模式。
適用原型模式可以對客戶隱藏產(chǎn)品的具體類,因此減少了客戶知道的名字的數(shù)目,此外是客戶無需改變
原型模式的缺陷是每個原型的子類都必須實現(xiàn)Cloneable接口,這個實現(xiàn)起來有時候比較困難。

3.效果
(1).創(chuàng)建型模式
(2).運行時刻增加和刪除產(chǎn)品
(3).改變只以指定新對象(ctrl+v,然后修改)
(4).改變結構以指定新對象。(類似2,實現(xiàn)不同而已)
(5).減少子類的構造


當前題目:Android設計模式系列--原型模式
URL地址:http://www.5511xx.com/article/codhido.html