Android设计模式系列(10)--SDK源码之原型模式

来源:互联网 发布:轰动一时 知乎 编辑:程序博客网 时间:2024/04/29 14:50

来自http://www.cnblogs.com/qianxudetianxia/archive/2012/03/02/2020355.html


CV一族,应该很容易理解原型模式的原理,复制,粘贴完后看具体情况是否修改,其实这就是原型模式。
从java的角度看,一般使用原型模式有个明显的特点,就是实现cloneable的clone()方法。
原型模式,能快速克隆出一个与已经存在对象类似的另外一个我们想要的新对象。

1.意图
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
热门词汇:克隆 深拷贝 浅拷贝

2.结构图和代码
它的结构图非常简单,我们以Intent为例子:


Intent的clone方法非常简单:

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

返回一个新的Intent对象。
克隆操作分深拷贝和浅拷贝,浅拷贝说白了就是把原对象所有的值和引用直接赋给新对象。深拷贝则不仅把原对象的值赋给新对象,而且会把原对象的引用对象也重新创建一遍再赋给新对象。
我们具体分析一下Intent是浅拷贝还是深拷贝吧:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 HashSet<String>(o.mCategories);
    }
    if (o.mExtras != null) {
        this.mExtras = new Bundle(o.mExtras);
    }
    if (o.mSourceBounds != null) {
        this.mSourceBounds = new Rect(o.mSourceBounds);
    }
}

这里我们为什么Intent要重写Object的clone方法,就与深拷贝有关。
其实我们查看Object的clone()方法源码和注释,默认的super.clone()用的就是浅拷贝:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
 * 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);
}

这种形式属于简单形式的原型模式,如果需要创建的原型数目不固定,可以创建一个原型管理器,在复制原型对象之前,客户端先在原型管理器中查看
是否存在满足条件的原型对象,如果有,则直接使用,如果没有,克隆一个,这种称作登记形式的原型模式。
适用原型模式可以对客户隐藏产品的具体类,因此减少了客户知道的名字的数目,此外是客户无需改变
原型模式的缺陷是每个原型的子类都必须实现Cloneable接口,这个实现起来有时候比较困难。

3. 效果
(1).创建型模式
(2).运行时刻增加和删除产品
(3).改变只以指定新对象(ctrl+v,然后修改)
(4).改变结构以指定新对象。(类似2,实现不同而已)
(5).减少子类的构造