using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AnimalWorld
{
abstract class ContinentFactory
{
abstract public Herbivore CreateHerbivore();
abstract public Carnivore CreateCarnivore();
}
//非洲大陆.
class AfricaFactory : ContinentFactory
{
public override Herbivore CreateHerbivore()
{
return new Wildebeest();
//throw new NotImplementedException();
}
public override Carnivore CreateCarnivore()
{
return new Lion();
//throw new NotImplementedException();
}
}
//美洲大陆.
class AmericaFactory : ContinentFactory
{
override public Herbivore CreateHerbivore()
{
return new Bison();
}
public override Carnivore CreateCarnivore()
{
return new Wolf();
//throw new NotImplementedException();
}
}
//食草动物.
abstract class Herbivore
{
}
//食肉动物.
abstract class Carnivore
{
abstract public void Eat(Herbivore h);
}
//角马.
class Wildebeest : Herbivore
{
}
//狮子.
class Lion : Carnivore
{
public override void Eat(Herbivore h)
{
Console.WriteLine(this + " eats " + h);
//throw new NotImplementedException();
}
}
//野牛.
class Bison : Herbivore
{
}
//狼.
class Wolf : Carnivore
{
public override void Eat(Herbivore h)
{
Console.WriteLine(this + " eats " + h);
//throw new NotImplementedException();
}
}
//动物世界.
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();
}
}
}
从书上看的,记录下来。