设计模式原型模式

1.原型模式的定义及使用场景
定义:
用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象
使用场景:
类初始化需要消耗非常多的资源,这个资源包括数据、硬件资源等,通过原型拷贝避免这些消耗
通过new产生一个对象需要非常繁琐的数据准备或访问权限,这时可以使用原型模式
一个对象需要提供给其他对象访问,而且各个调用者可能都需要修改其值时,可以考虑使用原型模式拷贝多个对象供调用者使用,即保护性拷贝

《设计模式原型模式》 Paste_Image.png

2.原型模式的优缺点

2.1优点

性能优良原型模式是在内存二进制流的拷贝,要比直接new一个对象性能好,特别是要在一个循环体内产生大量的对象时,原型模式可以更好地体现其优点

2.2缺点

逃避构造函数的约束这既是他的优点也是缺点,直接在内存中拷贝,构造函数不会执行。需要在实际应用时考虑

3.注意实现

构造函数默认不执行

浅拷贝及深拷贝

Object类提供的方法clone只是拷贝本对象,其对象内部的数组、引用对象等都不拷贝,还是指向原型对象的内部元素地址,这种拷贝为浅拷贝。如需要深拷贝,对应的成员也需指向clone方法

要使用clone方法,类的成员变量上不要增加final关键字

4.原型模式的实现方式

ProtoType:

public class ProtoType implements Cloneable {  
  
  
    public ProtoType() {  
        System.out.println("ProtoType is excute...");  
    }  
  
  
    private int id;  
    private String name;  
  
  
    public int getId() {  
        return id;  
    }  
  
  
    public void setId(int id) {  
        this.id = id;  
    }  
  
  
    public String getName() {  
        return name;  
    }  
  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
  
    @Override  
    protected ProtoType clone() {  
        ProtoType protoType = null;  
        try {  
            protoType = (ProtoType) super.clone();  
        } catch (CloneNotSupportedException e) {  
            e.printStackTrace();  
        }  
        return protoType;  
    }  
  
  
    @Override  
    public String toString() {  
        return "ProtoType{" +  
                "id=" + id +  
                ", name='" + name + '\'' +  
                '}';  
    }  
}```
Text:

public class Test {

public static void main(String args[]) {  
    ProtoType type = new ProtoType();  
    type.setId(1);  
    type.setName("张三");  
    System.out.println(type);  
    ProtoType clone = type.clone();  
    clone.setId(2);  
    clone.setName("李四");  
    System.out.println(clone);  
}  

}“`
Objec的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. 
* 
* @return a copy of this object. 
* @throws CloneNotSupportedException 
* if this object's class does not implement the {@code 
* Cloneable} interface. 
*/  
protected Object clone() throws CloneNotSupportedException {  
if (!(this instanceof Cloneable)) {  
throw new CloneNotSupportedException("Class " + getClass().getName() +  
" doesn't implement Cloneable");  
}  
return internalClone();  
}  
/* 
* Native helper method for cloning. 
*/  
private native Object internalClone();```
可见执行了一个native方法执行二进制流的拷贝
**5.原型模式在Android中的实际应用**
Intent:

@Override
public Object clone() {
return new Intent(this);
}

/**

  • 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;
    this.mContentUserHint = o.mContentUserHint;
    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);
    }
    }“`
    出处:http://huangjunbin.com/page/2/
    原文作者:GB_speak
    原文地址: https://www.jianshu.com/p/c5c3c76304f3
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞