赞
踩
原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。
原型模式参与者:
Prototype:原型类,声明一个Clone自身的接口;
ConcretePrototype:具体原型类,实现一个Clone自身的操作。
在原型模式中,Prototype通常提供一个包含Clone方法的接口,具体的原型ConcretePrototype使用Clone方法完成对象的创建。
- public abstract class Prototype
- {
- private string _id;
-
- public Prototype(string id)
- {
- this._id = id;
- }
-
- public string Id
- {
- get { return _id; }
- }
-
- public abstract Prototype Clone();
- }

- public class ConcretePrototype1:Prototype
- {
- public ConcretePrototype1(string id)
- : base(id)
- {
- }
-
- public override Prototype Clone()
- {
- return (Prototype)this.MemberwiseClone();
- }
- }
- public class ConcretePrototype2:Prototype
- {
- public ConcretePrototype2(string id)
- : base(id)
- {
- }
-
- public override Prototype Clone()
- {
- return (Prototype)this.MemberwiseClone();
- }
- }
- class Client
- {
- static void Main(string[] args)
- {
- ConcretePrototype1 p1 = new ConcretePrototype1("I");
- ConcretePrototype1 c1 = (ConcretePrototype1)p1.Clone();
- Console.WriteLine("Cloned: {0}", c1.Id);
-
- ConcretePrototype2 p2 = new ConcretePrototype2("II");
- ConcretePrototype2 c2 = (ConcretePrototype2)p2.Clone();
- Console.WriteLine("Cloned: {0}", c2.Id);
- Console.Read();
- }
- }
- public abstract class MobilePhonePrototype
- {
- private string _brand;
-
- public string Brand
- {
- get { return _brand; }
- }
-
- public MobilePhonePrototype(string brand)
- {
- this._brand = brand;
- }
-
- public abstract MobilePhonePrototype Clone();
-
-
- }

- public class XiaoMiPrototype:MobilePhonePrototype
- {
- public XiaoMiPrototype(string brand)
- : base(brand)
- {
-
- }
-
- public override MobilePhonePrototype Clone()
- {
- return (MobilePhonePrototype)this.MemberwiseClone();
- }
- }
- public class ApplePrototype:MobilePhonePrototype
- {
- public ApplePrototype(string brand)
- : base(brand)
- {
- }
-
- public override MobilePhonePrototype Clone()
- {
- return (MobilePhonePrototype)this.MemberwiseClone();
- }
- }
- class Client
- {
- static void Main(string[] args)
- {
- XiaoMiPrototype xiaomi = new XiaoMiPrototype("小米");
- XiaoMiPrototype xiaomi2 = (XiaoMiPrototype)xiaomi.Clone();
- Console.WriteLine(xiaomi2.Brand);
-
- ApplePrototype iphone = new ApplePrototype("iPhone7 Plus");
- ApplePrototype iphone2 = (ApplePrototype)iphone.Clone();
- Console.WriteLine(iphone2.Brand);
- Console.Read();
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。