抽象工厂 AbstractFactory

类图

抽象工厂 AbstractFactory_第1张图片

interface AbstractFactoryPattern { ICommodity MakeCommodity(Commodity commodity); IFood MakeFood(Food food); }

抽象工厂接口

using System; class FoodAndCommodityFactory : AbstractFactoryPattern { #region AbstractFactoryPattern 成员 public ICommodity MakeCommodity(Commodity commodity) { switch (commodity) { case Commodity.Cap: return new Cap(); break; case Commodity.Shoes: return new Shoes(); break; case Commodity.Sock: return new Sock(); break; case Commodity.Trousers: return new Trousers(); break; default: throw new Exception("参数无效"); } } public IFood MakeFood(Food food) { switch (food) { case Food.Chips: return new Chips(); break; case Food.Fish: return new Fish(); break; case Food.Hamburger: return new Hamburger(); break; case Food.SandWich: return new SandWich(); break; default: throw new Exception("参数无效"); } } #endregion }

抽象工厂接口实现者

interface IFood { void Print(); }

食物接口

using System; class Chips : IFood { #region IFood 成员 public void Print() { Console.WriteLine("Im chips!"); } #endregion }

食物A

using System; class Fish : IFood { #region IFood 成员 public void Print() { Console.WriteLine("Im Fish"); } #endregion }

食物B

using System; class SandWich : IFood { #region IFood 成员 public void Print() { Console.WriteLine("Im a SandWich!"); } #endregion }

食物C

interface ICommodity { void Print(); }

产品接口

using System; class Cap : ICommodity { public Cap() { } public void Print() { Console.WriteLine("Im a Cap!"); } }

产品实现A

using System; class Shoes:ICommodity { public Shoes() { } public void Print() { Console.WriteLine("Im a Shoes!"); } }

产品实现B

 using System; class Sock : ICommodity { public Sock() { } public void Print() { Console.WriteLine("Im a Sock!"); } }

产品实现C

using System; class Trousers : ICommodity { public Trousers() { } public void Print() { Console.WriteLine("Im Trousers!"); } }

产品实现D

using System; using System.Collections.Generic; using System.Text; namespace FactoryPattern { class Program { static void Main(string[] args) { ICommodity commodity; IFood food; //抽象工厂 FoodAndCommodityFactory facf = new FoodAndCommodityFactory(); commodity= facf.MakeCommodity(Commodity.Cap); food = facf.MakeFood(Food.Chips); commodity.Print(); food.Print(); Console.ReadKey(); } } }

调用代码

你可能感兴趣的:(Pattern,&,Practice)