- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- class CRunMain
- {
- public static void Main()
- {
- // 创建并运行非洲动物世界
- IContinentFactory objAfrican = new CAfricaFactory();
- // 创建并运行美洲动物世界
- IContinentFactory objAmerican = new CAmericaFactory();
- CAnimalWorld objAfricanWorld = new CAnimalWorld(objAfrican);
- CAnimalWorld objAmericanWorld = new CAnimalWorld(objAmerican);
- Console.WriteLine("非洲世界....");
- objAfricanWorld.RunFoodchain();
- Console.WriteLine("/n美洲世界....");
- objAmericanWorld.RunFoodchain();
- }
- }
- class CAnimalWorld
- {
- public CAnimalWorld(IContinentFactory objFac)
- {
- m_objCarn = objFac.CreateCarnivore();
- m_objHervb = objFac.CreateHerbivore();
- }
- public void RunFoodchain()
- {
- m_objHervb.Eat();
- m_objCarn.Eat(m_objHervb);
- }
- private IHerbivore m_objHervb;
- private ICarnivore m_objCarn;
- }
- abstract class IContinentFactory//抽象工厂(大陆)
- {
- abstract public IHerbivore CreateHerbivore();//创建草食动物
- abstract public ICarnivore CreateCarnivore();//创建肉食动物
- }
- class CAfricaFactory : IContinentFactory //具体工厂(非洲)
- {
- public override IHerbivore CreateHerbivore()
- {
- return new CWildeBeest();
- }
- public override ICarnivore CreateCarnivore()
- {
- return new CLion();
- }
- }
- class CAmericaFactory : IContinentFactory //具体工厂(美洲)
- {
- public override IHerbivore CreateHerbivore()
- {
- return new CBison();
- }
- public override ICarnivore CreateCarnivore()
- {
- return new CWolf();
- }
- }
- abstract class IHerbivore//抽象产品(草食动物)
- {
- abstract public void Eat();
- }
- abstract class ICarnivore//抽象产品(食肉动物)
- {
- abstract public void Eat(IHerbivore objHerb);
- }
- class CWildeBeest : IHerbivore//产品(羚羊)
- {
- public override void Eat()
- {
- Console.WriteLine("羚羊吃草!");
- }
- public override string ToString()
- {
- return "羚羊";
- }
- }
- class CBison: IHerbivore
- {
- public override void Eat()
- {
- Console.WriteLine("野牛吃树叶!");
- }
- public override string ToString()
- {
- return "野牛";
- }
- }
- class CLion:ICarnivore
- {
- public override void Eat(IHerbivore objHerb)
- {
- Console.WriteLine("狮子吃" + objHerb);
- }
- public override string ToString()
- {
- return "狮子";
- }
- }
- class CWolf:ICarnivore
- {
- public override void Eat(IHerbivore objHerb)
- {
- Console.WriteLine("狼吃" + objHerb);
- }
- public override string ToString()
- {
- return "狼";
- }
- }
设置模式之抽象工厂模式(Abstract Factory) C#源代码
最新推荐文章于 2020-08-05 15:03:42 发布