标签:
抽象工厂 定义生产 抽象产品
具体工厂 重写实现 具体产品
一般会建多个类库,然后根据反射,读配置这些操作来动态的
生产我们需要的产品
当需要有新的产品时,当然这个产品要是我们前面定义的抽象产品的子类,
我们要做的就是
新增一个工厂类,并且实现抽象工厂
新增一个具体产品,并且实现抽象产品
4个角色:
1 interface AbstractFactory 2 { 3 //假设就生产刀 4 ProductDaoBase CreateDao(); 5 } 6 7 class FactoryA : AbstractFactory 8 { 9 public ProductDaoBase CreateDao() 10 { 11 return new ProductA(); 12 } 13 } 14 class FactoryB : AbstractFactory 15 { 16 17 public ProductDaoBase CreateDao() 18 { 19 return new ProductB(); 20 } 21 } 22 abstract class ProductDaoBase 23 { 24 public string Name { get; set; } 25 public abstract void Show(); 26 27 } 28 class ProductA : ProductDaoBase 29 { 30 public override void Show() 31 { 32 Console.WriteLine("ProductA的Show()方法"); 33 } 34 } 35 class ProductB : ProductDaoBase 36 { 37 public override void Show() 38 { 39 Console.WriteLine("ProductB的Show()方法"); 40 } 41 }
配置文件:
1 <?xml version="1.0" encoding="utf-8" ?> 2 <configuration> 3 <startup> 4 <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> 5 </startup> 6 <appSettings> 7 <add key="CurrentFactory" value="ConsoleApplication.FactoryA"/> 8 </appSettings> 9 </configuration>
客户端:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Configuration; 7 8 namespace ConsoleApplication 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 string currentFactory = ConfigurationManager.AppSettings["currentFactory"].ToString(); 15 Type type = Type.GetType(currentFactory); 16 if (type != null) 17 { 18 object obj = Activator.CreateInstance(type); 19 // ProductDaoBase productBase = (ProductDaoBase)obj; 20 AbstractFactory af = (AbstractFactory)obj; 21 ProductDaoBase productBase = af.CreateDao(); 22 productBase.Show(); 23 24 25 } 26 else 27 { 28 Console.WriteLine("配置或者读取配置得type有问题"); 29 } 30 31 } 32 } 33 }
标签:
原文地址:http://www.cnblogs.com/liyax/p/4918057.html