首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

原形模式(prototype)

2012-09-07 
原型模式(prototype)意图: 用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。结构图实现示例

原型模式(prototype)
意图: 用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。
结构图

实现示例:
原型Prototype:

public class Client {private Prototype prototype;public void setPrototype(Prototype prototype) {this.prototype = prototype;}public void runExample() throws Exception {Container c = new Container();ConcretePrototype1 item1 = null;item1 = (ConcretePrototype1)prototype.clone();item1.setDescription("this is item1");c.addItem(item1);ConcretePrototype1 item2 = null;item2 = (ConcretePrototype1)item1.clone();item2.setDescription("This is item2");c.addItem(item2);ConcretePrototype2 item3 = null;item3 = new ConcretePrototype2();item3.setFlag(100);c.addItem(item3);ConcretePrototype2 item4 = null;item4 = (ConcretePrototype2)item3.clone();item4.setFlag(500);c.addItem(item4);}public static void main(String args[]) throws Exception {Client client = new Client();client.setPrototype(new ConcretePrototype1());client.runExample();}}

执行结果:
Now items list:
Concrete 1 description: this is item1
Now items list:
Concrete 1 description: this is item1
Concrete 1 description: This is item2
Now items list:
Concrete 1 description: this is item1
Concrete 1 description: This is item2
Concrete 2 flag = 100
Now items list:
Concrete 1 description: this is item1
Concrete 1 description: This is item2
Concrete 2 flag = 100
Concrete 2 flag = 500

注:示例中原型Prototype只有一个属性,通过复制来创建没有体现其优势,当prototype中属性较多时,通过复制可以节省初始化的开销

热点排行