一.抽象工厂模式:设计模式
在工厂模式中具体的产品和具体的工厂是一一对应的,一个工厂只能生产一种产品,结构单一,例如小米公司刚开始是只生产小米手机,可是伴随着公司的发展,他们须要生产不一样型号的手机,也会生产路由器,小米电视等等,那么工厂方法模式已不能知足业务的需求了,此时咱们就须要抽象工厂模式,即一个工厂能够生产多种产品。ide
抽象产品:负责定义抽象工厂生成的产品的接口,在本例中有两个抽象产品类,分别是手机和电视的抽象类测试
public abstract class IMobilePhone { public abstract void dial(); } public abstract class ITelevision { public abstract void watchTV(); }
public class MobilePhone : IMobilePhone { private string name; public MobilePhone(string name) { this.name = name; Console.WriteLine("制做手机"+name); } public override void dial() { Console.WriteLine("使用" + name+"打电话"); } } public class Television : ITelevision { private string name; public Television(string name) { this.name = name; Console.WriteLine("制做电视"+name); } public override void watchTV() { Console.WriteLine("经过"+name+"看电视"); } }
public abstract class Factory { public static Factory getFactory(string classname) { Factory factory = null; try { factory = (Factory)Assembly.Load("设计模式").CreateInstance("设计模式." + classname); } catch (Exception e) { Console.WriteLine("没有找到 " + classname + "类。"); } return factory; } public abstract MobilePhone createMobilePhone(String type); public abstract Television createTelevision(String type); }
public class XiaoMiFactory:Factory { public override MobilePhone createMobilePhone(string type) { return new MobilePhone(type); } public override Television createTelevision(string type) { return new Television(type); } }
下面实际测试一下:this
static void Main(string[] args) { Factory factory = Factory.getFactory("XiaoMiFactory"); IMobilePhone mobilePhone1 = factory.createMobilePhone("小米2"); IMobilePhone mobilePhone2 = factory.createMobilePhone("小米5"); ITelevision television1 = factory.createTelevision("小米电视2"); ITelevision television2 = factory.createTelevision("小米电视3"); mobilePhone1.dial(); mobilePhone2.dial(); television1.watchTV(); television2.watchTV(); Console.ReadKey(); }
输出信息:spa