热门问题
时间线
聊天
视角
原型模式
来自维基百科,自由的百科全书
Remove ads
原型模式是创建型模式的一种[1]:117,其特点在于通过「复制」一个已经存在的实例来返回新的实例,而不是新建实例。被复制的实例就是我们所称的「原型」,这个原型是可定制的。

原型模式多用于创建复杂的或者耗时的实例,因为这种情况下,复制一个已经存在的实例使程序运行更高效;或者创建值相等,只是命名不一样的同类数据。
结构

在上面的UML类图中,Client
类提及Prototype
接口来克隆一个Product
。Product1
类通过创建自身复本来实现Prototype
接口。
UML序列图展示了运行时交互:Client
对象调用clone()
于prototype:Product1
对象之上,它创建并返回自身的一个复本(product:Product1
对象)。
示例
下面是Java例子:
/** Prototype Class **/
public class Cookie implements Cloneable {
public Object clone() throws CloneNotSupportedException {
//In an actual implementation of this pattern you would now attach references to
//the expensive to produce parts from the copies that are held inside the prototype.
return (Cookie) super.clone();
}
}
/** Concrete Prototypes to clone **/
public class CoconutCookie extends Cookie { }
/** Client Class**/
public class CookieMachine {
private Cookie cookie;//cookie必须是可复制的
public CookieMachine(Cookie cookie) {
this.cookie = cookie;
}
public Cookie makeCookie() {
try {
return (Cookie) cookie.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
public static void main(String args[]){
Cookie tempCookie = null;
Cookie prot = new CoconutCookie();
CookieMachine cm = new CookieMachine(prot); //设置原型
for(int i=0; i<100; i++)
tempCookie = cm.makeCookie();//通过复制原型返回多个cookie
}
}
下面是Python例子:
import copy
class Prototype():
def clone(self):
return copy.copy(self)
class Product(Prototype):
def __init__(self, number=0, **kwargs):
self.number = number
for key, value in kwargs.items():
self.__dict__[key] = value
class ProductCreator():
def __init__(self, proto):
self.proto = proto
self.number = proto.number
def __call__(self):
self.number += 1
r = self.proto.clone()
r.number = self.number
return r
product0 = Product()
product_creator = ProductCreator(product0)
products = [product0]
for i in range(1, 20):
products += [product_creator()]
Remove ads
参见
引用
外部链接
Wikiwand - on
Seamless Wikipedia browsing. On steroids.
Remove ads