定义:
提供一个创建一系列相关或相互依赖对象的接口,而无须指定它们具体的类。
结构:
抽象工厂类
具体工厂类
抽象产品类
具体产品类
例子:
代码:
interface SkinFactory { Button CreateButton(); TextField CreateTextField(); ComboBox CreateComboBox(); }
class SummerSkinFactory : SkinFactory { public Button CreateButton() { return new SummerButton(); } public TextField CreateTextField() { return new SummerTextField(); } public ComboBox CreateComboBox() { return new SummerComboBox(); } }
interface Button { void Display(); } interface ComboBox { void Display(); } interface TextField { void Display(); }
class SummerButton : Button { public void Display() { Console.WriteLine("显示浅蓝色按钮。"); } } class SummerComboBox : ComboBox { public void Display() { Console.WriteLine("显示蓝色边框组合框。"); } } class SummerTextField : TextField { public void Display() { Console.WriteLine("显示蓝色边框文本框。"); } }
运行
//使用抽象层定义 SkinFactory factory; Button bt; TextField tf; ComboBox cb; //读取配置文件 string factoryType = ConfigurationManager.AppSettings["factory"]; //反射生成对象 factory = (SkinFactory)Assembly.Load("AbstractFactorySample").CreateInstance(factoryType); bt = factory.CreateButton(); tf = factory.CreateTextField(); cb = factory.CreateComboBox(); bt.Display(); tf.Display(); cb.Display();