原始模型模式有两种形式:简单形式和登记形式。
简单形式的原始模型类图:

源代码:
public interface Prototype extends Cloneable {
Object clone();
}
public class ConcretePrototype implements Prototype {
public Object clone()
{
System.out.println("return new ConcretePrototype()");
return new ConcretePrototype();
}
}
public class Client {
public static void main(String[] args) {
Prototype thePrototype = new ConcretePrototype();
Prototype pt1 = (Prototype)thePrototype.clone();
}
}
登记形式的原始模型模式类图:

其中:
原型管理器(PrototypeManager)角色:创建具体原型类的对象,并记录每一个被创建的对象。
源代码:
public interface Prototype extends Cloneable {
Object clone();
}
public class ConcretePrototype implements Prototype {
public Object clone()
{
return new ConcretePrototype();
}
}
public class PrototypeManager {
private Vector arrPrototype = new Vector();
public void addPrototype(Prototype pt)
{
arrPrototype.add(pt);
}
public Prototype getPrototype(int index)
{
return (Prototype)arrPrototype.get(index);
}
public int getSize()
{
return arrPrototype.size();
}
}
public class Client {
public static void main(String[] args) {
PrototypeManager mgr = new PrototypeManager();
Prototype thePrototype = new ConcretePrototype();
Prototype pt1 = (Prototype)thePrototype.clone();
Prototype pt2 = (Prototype)thePrototype.clone();
mgr.addPrototype(pt1);
mgr.addPrototype(pt2);
System.out.println("" + mgr.getSize());
}
}
两种形式的比较:
如果需要创建的原型对象数目较少而且比较固定,用简单形式的原始原型模式;如果要创建的原型对象数目不固定,用登记形式的原始模型模式。
Prototype模式重在从自身复制自己创建新类。
本文深入探讨了原始模型模式的概念及其在软件设计中的应用,详细介绍了简单形式和登记形式的区别与实现方式,同时提供了源代码示例进行说明。
1828

被折叠的 条评论
为什么被折叠?



