原型设计模式(Prototype Pattern
?
?
不通过 new 关键字来产生一个对象,而是通过对象拷贝来实现的模式就叫做原型模式。(实现接口Cloneable,重写clone()方法)
?
代码:
Prototype.java
?
package org.prototype; public class Prototype implements Cloneable { @Override protected Prototype clone() { // TODO Auto-generated method stub Prototype clonePrototype = null; try { clonePrototype = (Prototype) super.clone(); } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return clonePrototype; }}??
?
?
Client.java
package org.prototype; public class Client { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Prototype prototype = new Prototype(); Prototype clonePrototype = prototype.clone(); } }?
?
?
注意:
eg: Prototype.java中有构造方法
public Prototype() { System.out.println("调用构造方法");}?
?
在Client.java中并不调用构造方法,仅在New的时候调用。
Prototype clonePrototype = prototype.clone();
?
其输出结果为:调用构造方法
?
eg: Prototype.java中有一个数组
private ArrayList<String> name = new ArrayList<String>(); public ArrayList<String> getName() { return name; } public void addName(String name) { this.name.add(name);}?
?
在Client中对数据进行两次设值
Prototype prototype = new Prototype(); prototype.addName("张三"); Prototype clonePrototype = prototype.clone(); clonePrototype.addName("李四"); System.out.println(prototype);?
?
输出结果为:[张三, 李四]
说明调用的是同一个内存地址,解决的办法,在clone方法中对数组或者对象进行拷贝。
clonePrototype = (Prototype) super.clone(); clonePrototype.name = (ArrayList<String>)this.name.clone();
?
?
输出结果为:[张三]
?
private final ArrayList<String> name = new ArrayList<String>()
定义成final时,在clone()方法中使用
clonePrototype.name = (ArrayList<String>)this.name.clone();
?
?
?
?????? 会产生异常
?
原型模式场景使用:
在实际项目中,原型模式很少单独出现,一般是和工厂方法模式一起出现,通过 clone的方法创建一个对象,然后由工厂方法提供给调用者。
?
原型模式的优点:
原型模式是内存二进制的拷贝,比new一个对象性能好多,特别是在一个循环体内产生大量对象时,更能体现其优点
这是优点也是缺点,在实际应用时需要考虑。
?
?