標籤:設計模式 android
1、定義:
用原型執行個體指定建立對象種類,並通過拷貝這些原型建立新的對象。
2、目的:
從一個對象建立另外一個可定製的對象,而不需要知道任何建立細節。
3、作用:
3.1、簡化對象的建立;
3.2 、對於處理大對象,效能上比new 高出很多。
4、分類:
4.1淺拷貝:拷貝對象中的基本的資料類型,對於數組、容器物件、引用對象等都不會拷貝。
4.2深拷貝:將所有類型進行拷貝。
5、注意:
5.1對象實現Cloneable介面,必須將Object clone() 方法改為public;
5.2對於基礎資料型別 (Elementary Data Type),其封裝類型,String不需要進行處理。他們進行的均是深拷貝。
6、簡單的demo:
淺拷貝:
package com.example.demo.Prototype;/** * 淺拷貝 * @author qubian * @data 2015年6月4日 * @email [email protected] * */public class Prototype implements Cloneable {private int num;private String name;public int getNum() {return num;}public void setNum(int num) {this.num = num;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic Object clone() {Prototype prototype = null;try {prototype = (Prototype) super.clone();} catch (CloneNotSupportedException e) {e.printStackTrace();}return prototype;}}
深拷貝:
package com.example.demo.Prototype;import java.util.ArrayList;import java.util.Vector;/** * 深拷貝 * @author qubian * @data 2015年6月4日 * @email [email protected] * */public class DeepPrototype implements Cloneable{private String name;private ArrayList<String> arrayList;private DeepObject deepObject;public String getName() {return name;}public void setName(String name) {this.name = name;}public ArrayList<String> getArrayList() {return arrayList;}public void setArrayList(ArrayList<String> arrayList) {this.arrayList = arrayList;}public DeepObject getDeepObject() {return deepObject;}public void setDeepObject(DeepObject deepObject) {this.deepObject = deepObject;}/** * clone 方法 */@SuppressWarnings("unchecked")@Overridepublic Object clone() {DeepPrototype prototype = null;try {prototype = (DeepPrototype) super.clone();prototype.arrayList=(ArrayList<String>) this.arrayList.clone();prototype.deepObject=(DeepObject) this.deepObject.clone();} catch (CloneNotSupportedException e) {e.printStackTrace();}return prototype;}class DeepObject implements Cloneable{String name;protected Object clone() {DeepObject deep=null;try {deep= (DeepObject) super.clone();} catch (CloneNotSupportedException e) {e.printStackTrace();}return deep;};}}
7、原型模式在Android中的運用:
最明顯的例子就是Intent,但是好像還未知其用處。
但是細看,居然還是new 的對象。
public class Intent implements Parcelable, Cloneable { /** * Copy constructor. */ 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; if (o.mCategories != null) { this.mCategories = new ArraySet<String>(o.mCategories); } if (o.mExtras != null) { this.mExtras = new Bundle(o.mExtras); } if (o.mSourceBounds != null) { this.mSourceBounds = new Rect(o.mSourceBounds); } if (o.mSelector != null) { this.mSelector = new Intent(o.mSelector); } if (o.mClipData != null) { this.mClipData = new ClipData(o.mClipData); } } @Override public Object clone() { return new Intent(this); }}
Android設計模式--原型模式