3)一個對象需要提供給其他對象訪問,而且各個調用者可能都需要修改其值時,可以考慮使用原型模式拷貝多個對象供調用者使用,即保護性拷貝
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); } }
新聞熱點
疑難解答