15_抽象工厂模式
2016-11-28 13:21:54 15 举报
《大话设计模式》-抽象工厂模式
作者其他创作
大纲/内容
class ConcreteFactory1 : AbstractFactory { public override AbstractProductA CreateProductA() { return new ProductA1(); } public override AbstractProductB CreateProductB() { return new ProductB1(); } }
ProductA 1
AbstractProductB
abstract class AbstractProductA { }
class ProductA1 : AbstractProductA { }
AbstractProductA
abstract class AbstractFactory { public abstract AbstractProductA CreateProductA(); public abstract AbstractProductB CreateProductB(); }
class Client { private AbstractProductA AbstractProductA; private AbstractProductB AbstractProductB; public Client(AbstractFactory factory) { AbstractProductB = factory.CreateProductB(); AbstractProductA = factory.CreateProductA(); } public void Run() { AbstractProductB.Interact(AbstractProductA); } }
Client
class ConcreteFactory2 : AbstractFactory { public override AbstractProductA CreateProductA() { return new ProductA2(); } public override AbstractProductB CreateProductB() { return new ProductB2(); } }
AbstractFactory
+CreateProductA()+CreateProductB()
ConcreteFactory 1
class ProductB2 : AbstractProductB { public override void Interact(AbstractProductA a) { Console.WriteLine(this.GetType().Name + \" interacts with \" + a.GetType().Name); } }
private static void Main(string[] args) { AbstractFactory factory1 = new ConcreteFactory1(); var client1 = new Client(factory1); client1.Run(); AbstractFactory factory2 = new ConcreteFactory2(); var client2 = new Client(factory2); client2.Run(); Console.Read(); }
abstract class AbstractProductB { public abstract void Interact(AbstractProductA a); }
ProductB 2
ProductB 1
ConcreteFactory 2
class ProductB1 : AbstractProductB { public override void Interact(AbstractProductA a) { Console.WriteLine(this.GetType().Name + \" interacts with \" + a.GetType().Name); } }
ProductA 2
class ProductA2 : AbstractProductA { }
0 条评论
下一页