using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Configuration;using System.Reflection;//抽象工厂方法namespace Abstract_Dactory{ ////// 客户端测试类 /// class Program { static void Main(string[] args) { //使用抽象层定义 SkinFactory factory; Button bt; TextFiled tf; ComBox cb; //读取配置文件 string factoryType = ConfigurationManager.AppSettings["factory"]; //反射生成对象 factory = (SkinFactory)Assembly.Load("Abstract_Dactory").CreateInstance(factoryType); bt = factory.CreateButton(); tf = factory.CReateTextFiled(); cb = factory.CreateComBox(); bt.Display(); tf.Display(); cb.Display(); Console.ReadKey(); } } ////// 按钮接口,充当抽象产品 /// internal interface Button { void Display(); } ////// Spring按钮类充当具体产品 /// class SpringButton:Button { public void Display() { Console.WriteLine("显示浅绿色按钮"); } } ////// Summer按钮类充当具体产品 /// class SummerButton : Button { public void Display() { Console.WriteLine("显示浅蓝色按钮"); } } ////// 文本框接口类,充当抽象产品 /// interface TextFiled { void Display(); } ////// Spring文本框充当具体产品 /// class SpringTextFiled : TextFiled { public void Display() { Console.WriteLine("显示浅绿色文本框"); } } ////// Summer文本框充当具体产品 /// class SummerTextFiled : TextFiled { public void Display() { Console.WriteLine("显示浅蓝色文本框"); } } ////// 组合框接口,充当抽象产品类 /// interface ComBox { void Display(); } ////// Spring组合框,充当具体产品 /// class SpringComBox : ComBox { public void Display() { Console.WriteLine("显示浅绿色组合框"); } } ////// Summer组合框,充当具体产品 /// class SummerComBox : ComBox { public void Display() { Console.WriteLine("显示浅蓝色组合框"); } } ////// 界面工厂接口,充当抽象工厂 /// interface SkinFactory { Button CreateButton(); TextFiled CReateTextFiled(); ComBox CreateComBox(); } ////// Spring皮肤工厂,充当具体工厂 /// class SpringSkinFactory : SkinFactory { public Button CreateButton() { return new SpringButton(); } public TextFiled CReateTextFiled() { return new SpringTextFiled(); } public ComBox CreateComBox() { return new SpringComBox(); } } ////// Summer皮肤工厂,充当具体工厂 /// class SummerSkinFactory : SkinFactory { public Button CreateButton() { return new SummerButton(); } public TextFiled CReateTextFiled() { return new SummerTextFiled(); } public ComBox CreateComBox() { return new SummerComBox(); } }}
App.config
总结:
1.更改皮肤只需修改配置文件
2.添加新皮肤只需添加新的具体工厂与新的一族组件原有的代码不需要修改,符合开闭原则