⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 animalworld.cs

📁 《深入浅出设计模式》的完整源代码
💻 CS
字号:
using System;
namespace AnimalWorld
{
	// 抽象大陆工厂
	abstract class ContinentFactory
	{
		abstract public Herbivore CreateHerbivore();
		abstract public Carnivore CreateCarnivore();
	}
	//非洲大陆,有角马,狮子
	class AfricaFactory : ContinentFactory
	{
		override public Herbivore CreateHerbivore()
		{
			return new Wildebeest();
		}
		override public Carnivore CreateCarnivore()
		{
			return new Lion();
		}
	}
	// 美洲大陆,有狼,野牛
	class AmericaFactory : ContinentFactory
	{
		override public Herbivore CreateHerbivore()
		{
			return new Bison();
		}
		override public Carnivore CreateCarnivore()
		{
			return new Wolf();
		}
	}
	//食草动物"
	abstract class Herbivore
	{
	}
	//肉食动物"
	abstract class Carnivore
	{
		//猎食食草动物的方法
		abstract public void Eat( Herbivore h );
	}
	//角马
	class Wildebeest : Herbivore
	{
	}
	//狮子"
	class Lion : Carnivore
	{
		//重载猎食食草动物的方法
		override public void Eat( Herbivore h )
		{
			Console.WriteLine( this + " eats " + h );
		}
	}
	//野牛
	class Bison : Herbivore
	{
	}
	//狼
	class Wolf : Carnivore
	{
		//重载猎食食草动物的方法
		override public void Eat( Herbivore h )
		{
			Console.WriteLine( this + " eats " + h );
		}
	}
	//动物世界类
	class AnimalWorld
	{
		private Herbivore herbivore;
		private Carnivore carnivore;
		// 创建两种动物分类
		public AnimalWorld( ContinentFactory factory )
		{
			carnivore = factory.CreateCarnivore();
			herbivore = factory.CreateHerbivore();
		}
		//运行食物链
		public void RunFoodChain()
		{
			//肉食动物猎食食草动物
			carnivore.Eat( herbivore );
		}
	}
	/// <summary>
	/// 抽象工厂模式客户应用测试
	/// </summary>
	class GameApp
	{
		[STAThread]
		static void Main(string[] args)
		{
			//创造并运行非洲动物世界
			ContinentFactory africa = new AfricaFactory();
			AnimalWorld world = new AnimalWorld( africa );
			world.RunFoodChain();
			//创造并运行美洲动物世界
			ContinentFactory america = new AmericaFactory();
			world = new AnimalWorld( america );
			world.RunFoodChain();
			Console.Read();
		}

	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -