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); } }
新闻热点
疑难解答