Android设计模式--原型模式

1、定义:

用原型实例指定创建对象种类,并通过拷贝这些原型创建新的对象。

2、目的:从一个对象创建另外一个可定制的对象,而不需要知道任何创建细节。

3、作用:

3.1、简化对象的创建;

3.2 、对于处理大对象,性能上比new 高出很多。

4、分类:

4.1浅拷贝:拷贝对象中的基本的数据类型,对于数组、容器对象、引用对象等都不会拷贝。

4.2深拷贝:将所有类型进行拷贝。

5、注意:

5.1对象实现Cloneable接口,必须将Object clone() 方法改为public;

5.2对于基本数据类型,其封装类型,String不需要进行处理。他们进行的均是深拷贝。

6、简单的demo:

浅拷贝:

package com.example.demo.Prototype;/** * 浅拷贝 * @author qubian * @data 2015年6月4日 * @email naibbian@163.com * */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 naibbian@163.com * */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);}}@Overridepublic Object clone() {return new Intent(this);}}

有时不但是必要的,而且是很有必要的。

Android设计模式--原型模式

相关文章:

你感兴趣的文章:

标签云: