码迷,mamicode.com
首页 > 其他好文 > 详细

工厂模式

时间:2015-12-30 21:51:41      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

class Car
    {
        private Engine _engine;

        public Engine engine
        {
            get { return _engine; }
            set { _engine = value; }
        }

        public void Drive()
        {
            _engine.launch();

            Console.Write("********既然发动机已经启动了,汽车也就启动了。");
        }
    }

 

class Engine
    {
        public virtual void launch()
        {

        }
    }

class GasolineEngine:Engine
    {
        public override void launch()
        {
            Console.Write("小汽车的汽油发动机已经启动了");
        }
    }

class SolarEngine : Engine
    {
        public override void launch()
        {
            Console.Write("小汽车的太阳能发动机已经启动了");
        }
    }

class NuclearEngine : Engine
    {
        public override void launch()
        {
            Console.Write("小汽车的核能发动机已经启动了");
        }
    }

 

interface IEngineFactory
    {
        Engine MakeEngine();
    }

    class GaosolineEngineFactory:IEngineFactory
    {
        public Engine MakeEngine()
        {
            return new GasolineEngine();
        }
    }

    class SolarEngineFactory : IEngineFactory
    {
        public Engine MakeEngine()
        {
            return new SolarEngine();
        }
    }

    class NuclearEngineFactory : IEngineFactory
    {
        public Engine MakeEngine()
        {
            return new NuclearEngine();
        }
    }

 

class Program
    {
        static void Main(string[] args)
        {
            Console.Write("请根据不同的动力G/S/N,来选择不同动力的小汽车");
            string Select = Console.ReadLine();

            IEngineFactory enginefactory = null;

            switch (Select)
            {
                case "G":
                    enginefactory = new GaosolineEngineFactory();
                    break;
                case "S":
                    enginefactory = new SolarEngineFactory();
                    break;
                case "N":
                    enginefactory = new NuclearEngineFactory();
                    break;
            }

            Car car1 = new Car();
            car1.engine = enginefactory.MakeEngine();
            car1.Drive();
            Console.ReadLine();

        }
    }

 

工厂模式

标签:

原文地址:http://www.cnblogs.com/victorchi/p/5089973.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!