目录
- 定义
- UML
- 参与者
- 示例
定义:
定义一个创建对象的接口,但是让子类来决定哪个类将被实例化。工厂方法让一个类实例化推迟到子类。
UML:
参与者:
产品(Project)角色:定义一个产品的接口。
具体产品(ConcreteProduct)角色: 实现这个产品角色接口的具体类。
工厂(Factory)角色:定义一个接口,用来创建产品。
具体工厂(ConcreteFactory)角色:实现工厂角色接口的具体类。
示例
代码using System; namespace DoFactory.GangOfFour.Factory.Structural { /// <summary> /// MainApp startup class for Structural /// Factory Method Design Pattern. /// </summary> class MainApp { /// <summary> /// Entry point into console application. /// </summary> static void Main() { // An array of creators Creator[] creators = new Creator[2]; creators[0] = new ConcreteCreatorA(); creators[1] = new ConcreteCreatorB(); // Iterate over creators and create products foreach (Creator creator in creators) { Product product = creator.FactoryMethod(); Console.WriteLine("Created {0}", product.GetType().Name); } // Wait for user Console.ReadKey(); } } /// <summary> /// The 'Product' abstract class /// </summary> abstract class Product { } /// <summary> /// A 'ConcreteProduct' class /// </summary> class ConcreteProductA : Product { } /// <summary> /// A 'ConcreteProduct' class /// </summary> class ConcreteProductB : Product { } /// <summary> /// The 'Creator' abstract class /// </summary> abstract class Creator { public abstract Product FactoryMethod(); } /// <summary> /// A 'ConcreteCreator' class /// </summary> class ConcreteCreatorA : Creator { public override Product FactoryMethod() { return new ConcreteProductA(); } } /// <summary> /// A 'ConcreteCreator' class /// </summary> class ConcreteCreatorB : Creator { public override Product FactoryMethod() { return new ConcreteProductB(); } } }
Output:
Created ConcreteProductA
Created ConcreteProductB
实际运用:
代码 /// <summary> /// 产品接口 /// </summary> public interface ICar { void OpenDoor(); } /// <summary> /// 宝马车 /// </summary> public class BaoMaCar : ICar { public void OpenDoor() { Console.WriteLine("打开宝马车门"); } } /// <summary> /// 奥迪车 /// </summary> public class AodiCar : ICar { public void OpenDoor() { Console.WriteLine("打开奥迪车门"); } } /// <summary> /// 工厂接口,用来创建哪个车 /// </summary> public interface IFactory { ICar Create(); } /// <summary> /// 宝马工厂 /// </summary> public class BaoMaFactory : IFactory { public ICar Create() { return new BaoMaCar(); } } /// <summary> /// 奥迪工厂 /// </summary> public class AoDiFactory : IFactory { public ICar Create() { return new AodiCar(); } } static void Main(string[] args) { IFactory factory = new AoDiFactory(); ICar car = factory.Create(); car.OpenDoor(); Console.Read(); }
OutPut:
打开奥迪车门