原型是相对于复制、克隆而言,但是不同于模板,模板创造出的东西是一模一样, 而原型创造的东西是允许差异化和个性化存在,这就是原型。 原型模式最为核心的两点是:拷贝、属性更新; 拷贝指深拷贝copy.deepcopy,属性更新是类的自有属性__dict__的更新。
python的原型模式实现
import copy
class Information:
def __init__(self):
self.name = None
self.age = None
self.height = None
def run(self):
print("i'm {} age {} height{}".format(self.name,self.age,self.height))
class Prototype:
def __init__(self,obj):
self.copy_object = obj()
def clone(self,**attr):
obj = copy.deepcopy(self.copy_object)
obj.__dict__.update(attr)
return obj
test = Prototype(Information)
a = test.clone(name='aname',height="149",age="13")
a.run()
dart 实现
abstract class Prototype {
Prototype clone();
}
class ConcretePrototype implements Prototype {
String _name;
ConcretePrototype(this._name);
sayHello() {
print("hello ${this._name}");
}
@override
Prototype clone() {
// TODO: implement clone
return ConcretePrototype(_name);
}
}
main() {
ConcretePrototype p1 = ConcretePrototype("abc");
Prototype p2 = p1.clone();
p1.sayHello();
(p2 as ConcretePrototype).sayHello();
print(identical(p1, p2));
}
运行结果
[Running] dart "e:\source\dart\designpatterns\prototype.dart" hello abc hello abc false