初学设计模式 之 简单工厂(simple factory)

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            LightSimpleFactory lf = new LightSimpleFactory();
            light l = lf.create("bulb");
            l.TurnOn();
            l.TurnOff();
           Console.WriteLine("Press any key to exit...");
           Console.Read();
        }

    }
    public abstract class light
    {
        public abstract void TurnOn();
        public abstract void TurnOff();
       protected void hello()
        {
            Console.WriteLine("Hello world");
        }
    }
    public class TubeLight : light
    {
        public override void TurnOff()
        {
            Console.WriteLine("tubelight was turned off");
        }
        public override void TurnOn()
        {
            Console.WriteLine("tubelight was turned on");
       }    

    }
    public class BulbLight : light
    {
        public override void TurnOff()
        {
            Console.WriteLine("Bulblight was turned off");
        }
        public override void TurnOn()
        {
            Console.WriteLine("Bulblight was turned on");
        }
    }

    public class LightSimpleFactory
    {
        public light create(string lightType)
        {
            if (lightType == "tube")
                return new TubeLight();
            else if (lightType == "bulb")
                return new BulbLight();
            else
                return null;
        }
    }

}

posted @ 2009-07-16 10:33  大有  阅读(145)  评论(0)    收藏  举报