Prototype模式的意图是:
通过给出一个原型对象来指明所要创建的对象类型,然后用复制这个原型对象的办法创建出更多的同类型对象。
在java的类库中已经实现了这一模式,只要你定义的类实现了Cloneable接口,用这个类所创建的对象可以做为原型对象进而克隆出更多的同类型的对象。下面举个例子,来介绍简单的介绍一下它的使用。
浅克隆的测试结果:
Source : Source
Clone0,com.test1.prototype.Person@12b6651
Clone1,com.test1.prototype.Person@12b6651
Clone2,com.test1.prototype.Person@12b6651
Clone3,com.test1.prototype.Person@12b6651
Clone4,com.test1.prototype.Person@12b6651
Clone5,com.test1.prototype.Person@12b6651
Clone6,com.test1.prototype.Person@12b6651
Clone7,com.test1.prototype.Person@12b6651
Clone8,com.test1.prototype.Person@12b6651
Clone9,com.test1.prototype.Person@12b6651
Clone10,com.test1.prototype.Person@12b6651
Clone11,com.test1.prototype.Person@12b6651
Clone12,com.test1.prototype.Person@12b6651
Clone13,com.test1.prototype.Person@12b6651
Clone14,com.test1.prototype.Person@12b6651
Clone15,com.test1.prototype.Person@12b6651
Clone16,com.test1.prototype.Person@12b6651
Clone17,com.test1.prototype.Person@12b6651
Clone18,com.test1.prototype.Person@12b6651
Clone19,com.test1.prototype.Person@12b6651
可见,克隆目标引用的对象Person被克隆后全部指向同一对象,即原对象;
-------------------------------------------------------------------------------------------------
深克隆 :
将main中的clones[i] = (Prototype)source.clone();
改为clones[i] = (Prototype)source.deepClone();
深克隆的测试结果:
Source : Source
Clone0,com.test1.prototype.Person@16672d6
Clone1,com.test1.prototype.Person@fd54d6
Clone2,com.test1.prototype.Person@1ccb029
Clone3,com.test1.prototype.Person@1415de6
Clone4,com.test1.prototype.Person@7bd9f2
Clone5,com.test1.prototype.Person@121cc40
Clone6,com.test1.prototype.Person@1e893df
Clone7,com.test1.prototype.Person@443226
Clone8,com.test1.prototype.Person@1386000
Clone9,com.test1.prototype.Person@26d4f1
Clone10,com.test1.prototype.Person@1662dc8
Clone11,com.test1.prototype.Person@147c5fc
Clone12,com.test1.prototype.Person@3eca90
Clone13,com.test1.prototype.Person@64dc11
Clone14,com.test1.prototype.Person@1ac1fe4
Clone15,com.test1.prototype.Person@161d36b
Clone16,com.test1.prototype.Person@17f1ba3
Clone17,com.test1.prototype.Person@1ef8cf3
Clone18,com.test1.prototype.Person@ecd7e
Clone19,com.test1.prototype.Person@1d520c4
可见,克隆目标引用的对象Person被克隆后创建了新的对象。