原始模型模式屬於對象的建立模式,通過給出一個原型對象來指明所要建立的對象的類型,然後用複製這個原型對象的辦法建立出更多同類型的對象。
原始模型模式有兩種形式:簡單形式和登記形式。
簡單形式的原始模型類圖:
原始碼:
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());
}
}
兩種形式的比較:
如果需要建立的原型對象數目較少而且比較固定,用簡單形式的原始原型模式;如果要建立的原型對象數目不固定,用登記形式的原始模型模式。
三種常用建立型模式的比較:
Builder模式重在複雜物件的一步步建立(並不直接返回對象),AbstractFactory模式重在產生多個相互依賴類的對象,而Prototype模式重在從自身複製自己建立新類。