抽象工厂的一个例子

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();
        }
    }
}

从书上看的,记录下来。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值