原型模式(Prototype Pattern)是用于创建重复的对象
,同时又能保证性能。这种类型的设计模式属于创建型模式
,它提供了一种创建对象的最佳方式。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。
克隆
abstract class ProtoType{
String _id;
ProtoType(this._id);
String get id=>_id;
void set id(String id)=>this._id=id;
ProtoType clone();
}
class ConcretePrototype extends ProtoType{
ConcretePrototype(String id,this.name) : super(id);
final String name;
@override
ConcretePrototype clone() {
ProtoType protoType = new ConcretePrototype(this.id,this.name);
return protoType;
}
}
class RunPrototype implements Run {
@override
main(){
var a= ConcretePrototype("1","protoType模式");
var b= a.clone();
print("实例a的hashCode:"+a.hashCode.toString());
print("实例b的hashCode:"+b.hashCode.toString());
print("实例a的name:"+a.name);
print("实例b的name:"+b.name);
}
@override
String name="原型模式";
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。