C#-simple factory design pattern detailed

1. Basic concepts

As we all know, C# is an object-oriented language, and encapsulation, inheritance, and polymorphism are the three important characteristics of object-oriented. The simple factory design pattern can fully reflect these characteristics. To thoroughly understand this pattern, you must first understand all of encapsulation (application of access modifiers), inheritance (concepts of base classes and derived classes), and polymorphism (concepts of overloading, virtual methods, overriding, and abstract methods) , And can be used flexibly.

1. Simple factory model definition

The simple factory pattern is simply to create a factory class, create an object through the input parameters and assign values ​​to the base class, complete the call to the desired derived class, so as to achieve the goal, the specific operations are completed in the subclass, the factory class only Responsible for computing logic and assigning values ​​to the base class. This pattern has three parts:
1. Factory class: implements the selection type of creating all instances and the interface called by the outside world.
2. Abstract class: the base class of the class to be created, describing the common interface (method) common to all instances of the class, which can be an abstract class or an interface type (interface), this example is an abstract class.
3. Concrete class: all concrete instance objects to be created.
Why use the simple factory model? According to my understanding, the reason is as follows:
usually there are many objects that need to be faced, so many classes will be generated, and the objects of the class need to be instantiated. Think about it, if each class is in the main To instantiate in the function, it needs to write a lot of code, so it needs to be achieved through polymorphic methods. In addition, the subclass object is instantiated through the method of the factory class, that is, the base class is assigned to call the subclass method .

2. Examples

For example, when you go to dinner, you want to ask how long a certain meal will be ready, and you also want to know about the recipe. There are many types to choose from, such as braised chicken rice, Henan stewed noodles, dumplings, etc. If you want to " arbitrarily " shout a name of a meal to get an answer, you need to implement the factory model.
First of all, we must first create an abstract class, collectively refer to all types of rice as "Food", and create one or more abstract methods in the class. Note that if the base class is an abstract class, the subclass must be rewritten, which is why the abstract base class is created. You can arbitrarily achieve the desired effect in the subclass method.

    public abstract class Food
    {
        public abstract void Ask();
        public abstract void Menu();
    }

Then, create all subcategories, specific to each meal.

public class Rice : Food
    {
        public override void Ask()
        {
            Console.WriteLine("黄焖鸡米饭正在制作中,还需1分钟");
        }
        public override void Menu()
        {
            Console.WriteLine("鸡,米,油,盐,酱油,海带丝,香菇,辣椒");
        }
    }

    public class Noodles: Food
    {
        public override void Ask()
        {
            Console.WriteLine("河南烩面正在制作中,还需1小时");
        }
        public override void Menu()
        {
            Console.WriteLine("面,羊肉汤,葱花,盐");
        }
    }

    public class Dumplings : Food
    {
        public override void Ask()
        {
            Console.WriteLine("饺子正在制作中,还需1天");
        }
        public override void Menu()
        {
            Console.WriteLine("韭菜,鸡蛋,油,盐");
        }
    }

Then, the core part comes, the method to be implemented to create the factory class, the format is: access modifier + static keyword + base class name + method name (parameter name), so that the subclass can assign values ​​to the base class Features.

       //简单工厂的核心,根据用户的输入创建对象赋值给父类
       public static class 老高饭庄
        {
            public static Food Cook(string Foodname)
            {
                Food f = null;
                switch (Foodname)
                {
                    case "黄焖鸡米饭":
                        f = new Rice();
                        break;
                    case "河南烩面":
                        f = new Noodles();
                        break;
                    case "韭菜鸡蛋饺子":
                        f = new Dumplings();
                        break;
                    default:
                        break;
                }
                return f;
            }
        }

Finally, in the main function to instantiate the factory class, we can see that the call to any subclass can be achieved through the factory class.

 static void Main(string[] args)
        {
            Console.WriteLine("请输入菜名:");
            string Foodname = Console.ReadLine();
             Food f = 老高饭庄.Cook(Foodname);
             f.Ask();
             f.Menu();
            Console.ReadKey();
        }

Program display
Insert picture description here

Three, summary

The advantage of this mode is that the call to any subclass object can be completed only by parameters, and it is easy to extend. The shortcomings are also obvious. If I want to add a class, then I must change the factory class to complete it, violating the opening and closing principle (a software entity should be open for extension and closed for modification).
Write this first, and continue to update later.

Guess you like

Origin blog.csdn.net/baidu_35536188/article/details/109575787