设计模式1-简单工厂模式

  简单工厂模式是个什么东西呢?嗯,废话,设计模式中的一种。首先,还是情景模拟一下:猫能叫‘汪’,狗能叫‘喵’;咦,说反了 (懒癌放了不想改),看官自己脑改吧。现在,你可以输入(‘猫’,‘狗’),然后展示对应叫声(当然了,我们这里不去讨论如何让电脑发出猫叫,狗吠的声音,打印出拟声词就行了),你会怎么去实现呢?当然,你也可以两个if语句搞定,甚至Class都不用创建。

            string input = Console.ReadLine();
            if (input == "")
            {
                Console.WriteLine("喵~~~~~~~~~~");
            }
            if (input == "")
            {
                Console.WriteLine("汪~汪~汪~");
            }
            Console.ReadKey();

当然了,现在可是面向对象编程,所以呢,我们需要修改一下:

 /// <summary>
        ////// </summary>
        public class Dog
        {
            public string Name { get; set; }
            public void Call()
            {
                Console.WriteLine("汪~汪~汪~");
            } 
        }
        /// <summary>
        ////// </summary>
        public class Cat
        {
            public string Name { get; set; }
            public void Call()
            {
                Console.WriteLine("喵~~~~~~~~~~");
            }
        }

然后修改一下代码:

 string input = Console.ReadLine();
            if (input == "")
            {
                var cat = new Cat();
                cat.Call();
            }
            if (input == "")
            {
                var dog = new Dog();
                dog.Call();
            }
            Console.ReadKey();

好了,到现在为止,一般写法就结束了。我们继续思考:我们在主程序里面既实例化了猫,又实例化了狗;如果在加入象、狮、虎、豹、狼、(狗)、(猫)、鼠呢(ps:刚好一副斗兽棋)?我们还得一个一个的加入if条件语句并且分别实例化一次,这就是所谓的耦合度高了,主程序所依赖的动物类太多了。我们继续进行修改,因为都是动物,基本都能叫,所有我们抽象一个动物类,具体类重写Call方法就行了,同时使用简单工厂进行改进:

 /// <summary>
        /// 动物
        /// </summary>
        public class Animal
        {
            public string Name { get; set; }
            public virtual void Call()
            {
                Console.WriteLine("动物叫");
            }
        }
        /// <summary>
        /// 工厂
        /// </summary>
        public class SimpleFactory
        {
            public Animal GetAnimal(string type)
            {
                switch (type)
                {
                    case "":
                        return new Cat();
                    case "":
                        return new Dog();
                    default:
                        return new Animal();

                }
            }
        }
    
 
 /// <summary>
        /// 执行程序
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            string input = Console.ReadLine();
            Animal animal = new SimpleFactory().GetAnimal(input);
            animal.Call();
            Console.ReadKey();
        }

我们把动物类的实例化移动到了简单工厂里面,这样主程序里面就只实例化了一个类--简单工厂类,减低了主程序与动物之间的耦合度(转移成了动物和工厂之间的耦合),动物的实例化放进了简单工厂里,由方法进行返回实例。

  好了,简单工厂就到这里。第一次写博客,写的不好是肯定的,好像很多东西都没能表述清楚,还望海涵。我学习设计模式的书籍为:大话设计模式,不评论好坏(他们都说还不错,我就去看的)。

posted @ 2019-01-04 17:46  RジP  阅读(112)  评论(0)    收藏  举报