简单工厂模式

 

使用场景:

1 使用时不用知道具体调用的类。

2 类初始化较复杂

使用情况如下:

简单工厂模式

SchoolFactory schoolFactory = new SchoolFactory();
School a = schoolFactory.CreateSchool(SchoolTypeEnum.普通中学);
a.Dosomething();
 a = schoolFactory.CreateSchool(SchoolTypeEnum.职业中学);
a.Dosomething();
a = schoolFactory.CreateSchool(SchoolTypeEnum.军校);
a.Dosomething();
a = schoolFactory.CreateSchool(SchoolTypeEnum.工厂);
a.Dosomething();
a = schoolFactory.CreateSchool(SchoolTypeEnum.饭店);
a.Dosomething();

实现代码如下:

    class SchoolFactory
    {
        public School CreateSchool(SchoolTypeEnum typename)
        {
            string schoolName = "建华";
            int age = 2;
            switch (typename)
            {
                case SchoolTypeEnum.普通中学:
                    return new OrdinaryMiddleSchool(schoolName + typename, age + 1);
                case SchoolTypeEnum.职业中学:
                    return new VocationalHighSchool(schoolName + typename, age + 2);
                case SchoolTypeEnum.军校:
                    return new MilitaryAcademy(schoolName + typename, age + 3);
                case SchoolTypeEnum.工厂:
                default:
                    return new Factory(schoolName + typename, age + 4);
            }
        }
    }
abstract class School
    {
        protected string _name;
        protected int _age;
        public School(string name, int age)
        {
            _name = name;
            _age = age;
        }

        public void Dosomething()
        {
            Introduce();
            Teching();
            Console.WriteLine("");
        }

        protected void Introduce()
        {
            Console.WriteLine(_name + " 建立" + _age + "年:");
        }

        public virtual void Teching()
        {
        }
    }

    class OrdinaryMiddleSchool : School
    {
        public OrdinaryMiddleSchool(string name, int age)
            : base(name, age)
        {

        }

        public override void Teching()
        {
            Console.WriteLine("教数学,语文,英语");
        }
    }
    class VocationalHighSchool : School
    {
        public VocationalHighSchool(string name, int age)
            : base(name, age)
        {

        }

        public override void Teching()
        {
            Console.WriteLine("教电焊,汽车维修,电脑操作,做菜");
        }
    }
    class MilitaryAcademy : School
    {
        public MilitaryAcademy(string name, int age)
            : base(name, age)
        {

        }

        public override void Teching()
        {
            Console.WriteLine( " 教武装越野,武器操作");
        }
    }
    class Factory : School
    {
        public Factory(string name, int age)
            : base(name, age)
        {

        }

        public override void Teching()
        {
            Console.WriteLine(" 教拧螺丝,扫地,端菜");
        }
    }
    enum SchoolTypeEnum
    {
        普通中学,
        职业中学,
        军校,
        工厂,
        饭店
    }

 

上一篇:Django(39)使用redis配置缓存


下一篇:反射机制调用指定属性