工厂方法模式
故事:
有个定制鞋子的工厂(还是那个工厂)(因为使用了设计模式应对了各种变化)效益比较好,决定把生产部门分成两个部门(休闲鞋部门/运动鞋部门)。每个部门生产相应的鞋子类型。
建模:
工厂运动鞋生产部门/工厂休闲鞋生产部门。
工厂前台接待处。
鞋子。
你还是这个工厂的客户。
类图:
实现:
HelpDesk
namespace FactoryMethod { public class HelpDesk { ArrayList al = new ArrayList(); public HelpDesk() { SportsShoesDepartment ss = new SportsShoesDepartment(); al.Add(ss); LeisureShoesDepartment ls = new LeisureShoesDepartment(); al.Add(ls); } public Shoes produceShoes(string shoesType) { Shoes shoes; Console.WriteLine("<工厂公告>客户需要的鞋子类型是:{0}\n", shoesType); foreach(ShoesFactoryDepartment sfd in al) { shoes = sfd.produceShoes(shoesType); if (shoes != null) { return shoes; } } return null; } } }
ShoesFactoryDepartment
namespace FactoryMethod { public abstract class ShoesFactoryDepartment { public abstract Shoes produceShoes(string shoesType); } }
SportsShoesDepartment
namespace FactoryMethod { public class SportsShoesDepartment: ShoesFactoryDepartment { public override Shoes produceShoes(string shoesType) { if (shoesType == "Sport") { return new SportShoes(); } else { return null; } } } }
LeisureShoesDepartment
namespace FactoryMethod { public class LeisureShoesDepartment: ShoesFactoryDepartment { public override Shoes produceShoes(string shoesType) { if (shoesType == "Leisure") { return new LeisureShoes(); } else { return null; } } } }
Program
namespace FactoryMethod { class Program { static void Main(string[] args) { HelpDesk helpDesk = new HelpDesk(); Console.WriteLine("请输入你想要的鞋子:Sport/Leisure"); string shoesType = Console.ReadLine(); Console.WriteLine("\n------进厂定制---------\n"); helpDesk.produceShoes(shoesType); Console.WriteLine("\n-------鞋子出厂--------\n"); } } }
效果: