前言
继续工厂模式高级版,抽象工厂模式。抽象工厂模式其实是从工厂方法模式拓展而来。在实际的生活中一个工厂的产品不可能是单一的,肯定是多种系列的产品。
介绍 - 抽象工厂模式
定义:(摘自百度百科~)为创建一组相关或相互依赖的对象提供一个接口,而且无需指定他们的具体类。
实现
继续上一篇的某淘鞋厂的例子。现在鞋厂的生意越做越大甚至还开了分厂,老板现在决定拓展业务,买衣服...夏天买T-Shirt,冬天买棉衣,下面看实现:
1.衣服
/// <summary> /// 衣服基类 /// </summary> public abstract class Clothes { public abstract string Name { get; } } /// <summary> /// T恤衫 /// </summary> public class TShirt : Clothes { public override string Name { get { return "T恤衫"; } } } /// <summary> /// 夹克衫 /// </summary> public class Jacket : Clothes { public override string Name { get { return "夹克衫"; } } }
2.鞋子
/// <summary> /// 鞋子基类 /// </summary> public abstract class Shoes { public abstract string Name { get; } } /// <summary> /// 凉鞋 /// </summary> public class Sandal : Shoes { public override string Name { get { return "凉鞋"; } } } /// <summary> /// 棉鞋 /// </summary> public class CottonPaddedShoes : Shoes { public override string Name { get { return "棉鞋"; } } }
3.工厂
/// <summary> /// 抽象工厂类 /// </summary> public abstract class Factory { /// <summary> /// 生产鞋子 /// </summary> /// <returns></returns> public abstract Shoes CreateShoes(); /// <summary> /// 生成衣服 /// </summary> /// <returns></returns> public abstract Clothes CreateClothes(); } /// <summary> /// 夏季工厂类 /// </summary> public class SummerFactory : Factory { public override Clothes CreateClothes() { return new TShirt(); } public override Shoes CreateShoes() { return new Sandal(); } } /// <summary> /// 冬季工厂类 /// </summary> public class WinterFactory : Factory { public override Clothes CreateClothes() { return new Jacket(); } public override Shoes CreateShoes() { return new CottonPaddedShoes(); } }
调用:
class Program { static void Main(string[] args) { Console.WriteLine("夏季工厂生产..."); //夏季工厂 Factory factory = new SummerFactory(); //制造鞋子,衣服 Shoes shoes = factory.CreateShoes(); Clothes cloth = factory.CreateClothes(); //看看生产的是 Console.WriteLine("生产:{0},{1}", shoes.Name, cloth.Name); Console.WriteLine("冬季工厂生产..."); //冬季工厂 Factory factory1 = new WinterFactory(); //制造鞋子 Shoes shoes1 = factory1.CreateShoes(); Clothes cloth1 = factory1.CreateClothes(); //看看生产的是 Console.WriteLine("生产:{0},{1}", shoes1.Name, cloth1.Name); Console.Read(); } }
结果:
时间: 2024-11-10 01:33:54