Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How do rookies use design patterns

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how Xiaobai uses design patterns". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought. Let's study and learn how Xiaobai uses design patterns.

Brief introduction

Factory pattern (Factory Pattern) is one of the most commonly used design patterns. This type of design pattern is a creative pattern, which provides the best way to create objects.

In factory mode, we do not expose the creation logic to the client when we create the object, but point to the newly created object by using a common interface.

classification

Factory patterns can be divided into three types, of which simple factories are generally not considered as a design pattern, but can be regarded as a special factory approach.

Simple factory

Factory method

Abstract factory

Scene analysis

Ordinary and boring words always make people want to sleep. Next, we use several situational cases to analyze them.

Simple factory

A way to create multiple entity classes directly through a Factory [factory class] class.

Time: February 19, 2021 place: classroom characters: student rookie, teacher, boss black skin

Xiaobai is a sophomore majoring in computer science. He is lazy and doesn't like to study. This morning, the first class was caught by the teacher for sleeping late, and this class happened to be Xiaobai's biggest headache in the computer class "C# Design pattern". In this way, the teacher began to ask questions in the middle of the class, and the rookie "gloriously" became the teacher's roll call.

The teacher smiled and said, "Xiaobai, please answer the questions on the screen."

Topic: please use c #, java, python, php or any other side to input two legal numbers and a legal symbol into the object programming language, and output the corresponding results.

Xiaobai took a look, this is what kind of topic, so simple, see I am not easy to catch, accompanied by the hands crackling tapping sound, a string of codes appear on the screen.

* * Calculator operation class * *

Public class Calculator {public double GetResult (double A, double B, string operate) {double result = 0d; switch (operate) {case "+": result = A + B; break; case "-": result = A-B Break; case "*": result = A * B; break; case "/": result = A / B; break; default: break;} return result;}}

Client code

Class Program {static void Main (string [] args) {Console.WriteLine ("Please enter a number A"); string a = Console.ReadLine (); Console.WriteLine ("Please enter a number B"); string b = Console.ReadLine (); Console.WriteLine ("Please select an action symbol (+, -, *, /)") String operate = Console.ReadLine (); Calculator box = new Calculator (); double result = box.GetResult (Convert.ToDouble (a), Convert.ToDouble (b), operate); Console.WriteLine (result); Console.ReadKey ();}}

Xiaobai: "teacher, I have written it."

Teacher: "Yes, it's well written." using the encapsulation of the three major object-oriented features, the computing method is encapsulated into a computing class, and multiple clients can reuse this class. But there are also a lot of questions, which students will answer. "

Black skin: "there are two problems with the code written by Xiaobai."

1. If you enter Amal10, the program will report an error without validating the input.

2. If the operation symbol is not entered in accordance with the regulations, it will also lead to an error. "

Teacher: "Black skin gave a very good answer, but these are only descriptions of business logic errors in the code." is there anyone who can see something deeper? "

Black skin: "teacher, please give me a hint."

Teacher: "this can be a little hidden, the teacher will give a hint." what if we add a new operation? "

Xiaobai immediately replied, "just add a new branch to switch."

Teacher: "of course there is nothing wrong with this, but the problem is that I just added a new operation symbol, but I need to make all the operations of addition, subtraction, multiplication and division participate in the compilation. If you accidentally modify other code in the process of modification," for example, changing the + sign to a-sign is not very bad, which violates the opening and closing principle [open to extension, closed to modification]. "

Xiao Bai scratched his head and asked, "Open and close principle, what is this?"

Teacher: "this is what you left behind if you don't listen carefully. Go back and study hard. Black skin, I wonder if your Get has reached the teacher's point?"

Black skin: "I know how to modify it. Xiaobai has realized the encapsulation of one of the three major object-oriented features, in fact, the other two features can be used together to complete the functions that the teacher wants."

Xiaobai: "Polymorphism and inheritance?"

Black skin: "Yes, you should have a feeling when I finish changing the program."

Public class Operate {public double NumberA {get; set;} public double NumberB {get; set;} public virtual double GetResult () {return 0;}} public class OperateAdd: Operate {public override double GetResult () {return this.NumberA + this.NumberB }} public class OperateSub: Operate {public override double GetResult () {return this.NumberA-this.NumberB;}}

Simple factory

Public class OperateFactory {public static Operate GetOperateFactory (string operate) {Operate fac = null; switch (operate) {case "+": fac = new OperateAdd (); break; case "-": fac = new OperateSub () Break; case "*": fac = new OperateMul (); break; case "/": fac = new OperateDiv (); break; default: break } return fac;}}

Black skin: "the first is an operation class, which has two Number attributes and a virtual method GetResult (). The four methods of addition, subtraction, multiplication and division inherit as subclasses of the operation class, rewrite the GetResult () method after inheritance, and call the An and B public properties of the base class for different mathematical operations."

Black skin: "then define a simple factory, static methods pass in operator parameters to get the actual business processing class, and the client gets the processing class to assign values to the parameters." in the last step, you should know how to do it. "

Xiaobai: "I see, then the client can call it this way."

Static void Main (string [] args) {Console.WriteLine ("Please select operation symbol (+, -, *, /)"); string operateStr = Console.ReadLine (); Operate operate = OperateFactory.GetOperateFactory (operateStr); operate.NumberA = 10; operate.NumberB = 4; double result = operate.GetResult (); Console.WriteLine (result) Console.ReadKey ();}

Teacher: "it seems that both students have mastered the use of simple factories. Next, I would like to ask a few questions to facilitate you to master this design pattern more quickly."

Teacher: "if we want to modify the logic of division, what should we do to increase the logic of the divisor 0?"

Xiaobai: "directly modify the OperateDiv class, which will not affect others."

Teacher: "what should we do if we want to add a root operation?"

Xiaobai: "add a new class, Operate root class, which describes the logic of root opening. You can add a new operator to the factory method. The new operation, a single class, will not affect other method bodies."

Xiaobai: "does the client need to make any changes?"

Teacher: "what changes the client wants to make, the client just needs to take care of its own affairs!"

Yes, the client doesn't care what the factory creates. The factory is a black box. As long as the client passes in parameters, the factory is responsible for [the process of instantiating the class] to the client after the content is produced.

Advantages / disadvantages

Factory classes with simple factory patterns typically use static methods to return different object instances by receiving different parameters. Without modifying the code, it is an unextensible advantage: the client can be exempted from the responsibility of creating product objects directly, rather than simply "consuming" the product. The simple factory model realizes the disadvantage of dividing responsibility in this way: because the factory class centralizes the creation logic of all instances, violates the principle of high cohesion responsibility allocation, and centralizes all the creation logic into one factory class; the classes it can create can only be considered in advance, and if you need to add a new class, you need to change the factory class.

Factory method

Time: February 19, 2021 afternoon venue: classroom characters: student rookie, teacher, boss black skin

Teacher: "We continue with the design pattern in the morning. In the morning we talk about the simple factory, and in the afternoon we talk about the next content factory method." A factory method is more or less the same as a simple factory, except that each instance that implements an abstract class (also called a product, that is, the four subclasses defined in the morning) has a corresponding factory to create. Students understand what the teacher said, and then look for a scene code to implement. The quickest thing to finish is the classroom reward. "

.... A few minutes passed.

Xiaobai: "teacher, I finished it."

Teacher: "OK, let's ask Xiaobai to explain the scene and the way to realize it."

I designed a pattern based on fruit as the scene.

1. Define an abstract class Fruit.cs that defines two abstract methods, printfColor () and printfName ().

2. Implement two different fruits that inherit the abstract class and override the abstract method.

3. Define a factory interface and define the interface method createFruit ()

4. Realize the creation of fruit examples in two different factories.

Fruit abstract class

Public abstract class Fruit {public abstract void PrintfColor (); public abstract void PrintfName ();} public class Apple: Fruit {public override void PrintfColor () {Console.WriteLine ("red");} public override void PrintfName () {Console.WriteLine (Apple);}}

Factory interface

Public interface IFruitFactory {Fruit CreateFruit ();} public class AppleFactory: IFruitFactory {public Fruit CreateFruit () {return new Apple ();}}

Client implementation

/ / Apple Factory IFruitFactory appleFac = new AppleFactory (); Fruit apple = appleFac.CreateFruit (); apple.PrintfColor (); apple.PrintfName / / Orange Factory IFruitFactory orangeFac = new OrangeFactory (); Fruit orage = orangeFac.CreateFruit (); orage.PrintfColor (); orage.PrintfName ()

Teacher: "it seems that Xiaobai students have a full understanding of the content of the morning, really good class in order to learn new knowledge." it's no good skipping classes. "

Teacher: "it's just that such a case is too simple, and maybe other students don't quite understand why it's like this. Let me give you an example of a real scene to facilitate your understanding." In the actual work process, we always use logging components, such as third-party components such as Nlog,Log4net, which support configurable multi-source output. When we add a "parameter output to the console" in the configuration file (json/xml), the program will output the content to the console, and when configuring a parameter input to the file, the program will output the content to the specified file. The implementation of this scenario is actually a typical factory approach. Let me analyze the process. "

1. Read the configuration file (json/xml)

2. Get all the configuration methods and cycle through

3. Determine the configuration type, if it is the configuration input to the file. New is a file log factory that passes configuration information as parameters to facilitate later method calls; if it is a configuration entered into the console. New, a log factory, does the same thing.

4. Each factory only manages its own business, but should have the interface of log output.

5. When the upper layer calls the print method, it iterates through all the factories and calls the log output method of the interface.

Advantages / disadvantages

The factory approach is to provide a factory class for each product. Create different product instances through different factory instances. Support the addition of any product advantage in the same hierarchical structure: allow the system to introduce new products without modifying specific factory roles: since each additional product requires the addition of a product factory class, additional development volume is added

Abstract factory

The abstract factory pattern provides a solution for creating a set of objects. Compared with the factory method pattern, the concrete factory in the abstract factory pattern is not just to create a product, it is responsible for creating a family of products.

Time: February 20, 2021 morning place: classroom characters: student rookie, teacher, black skin

A new day has begun. The course of "Design pattern" seems to be less complicated in the eyes of Xiaobai. Today, Xiaobai arrived in the classroom early, ready to meet the teacher's new spur.

Teacher: "good morning, students. Today we continue yesterday's lesson. Yesterday we talked about the factory method, and today we make some improvements on this basis to see what new changes there are. Xiaobai students are very enthusiastic about learning, and now they all know that they are sitting in the front row. Yes, it is worth encouraging."

Xiaobai: "hee hee"

Teacher: "OK, let's start today's lesson. Today's model is the abstract factory model. By comparing with the factory model, the students can see the difference between the two more clearly. Let's use yesterday's Xiaobai classmate's example to continue to develop."

At this time, there are two products, Apple and Orange, corresponding to Apple Factory and Orange Factory respectively. This is the embodiment of the factory method. But if there are three different factories, they all produce apples and oranges.

Xiaobai: "mm-hmm. then build more factories. Each product corresponds to a different factory, which should be such a structure, and each factory corresponds to the category of the product produced."

A

A _ Apple factory .cs

A _ orange factory .cs

B

B _ Apple Factory .cs

B _ orange factory .cs

C

C _ Apple Factory .cs

C _ orange factory .cs

Teacher: "of course, this way is OK, but if I have 10 factories, do we have to build 10-2-20 classes? so the complexity of the program will rise in a straight line, which is not conducive to maintenance."

Xiaobai: "what should I do, use the kind of abstract factory you mentioned by the teacher?" if so, what should be done? "

Teacher: "Yes, in such a scenario, the abstract factory is the best matching design pattern." in fact, the practice is very simple, just make some changes to yesterday's code. "

Fruit abstract class

Add a Name property to make it easy to print different factories later.

Public abstract class Fruit {public string Name {get; set;} public abstract void PrintfColor (); public abstract void PrintfName ();} public class Apple: Fruit {public Apple (string name) {this.Name = name;} public override void PrintfColor () {Console.WriteLine (this.Name + "red") } public override void PrintfName () {Console.WriteLine (this.Name + "Apple");}}

Factory interface

Teacher: "the change in this place is more obvious." The method in the original interface outputs a unique product-- because each factory previously produced only one product. Now output two products, that is, the class that inherits the factory interface must implement the method of producing apples and oranges. The advantage is that each factory is responsible for managing the implementation of its own products, avoiding the need to create a factory for each product. "

Explanation:

The factory produces apples and oranges. When there are multiple factories, each factory can produce apples and oranges. Instead of producing factory An Apple needs a factory implementation class, and factory B needs another one. As shown below

Old model

A

A _ Apple Factory.

A _ orange factory

B

B _ Apple Factory

B _ orange factory

C

C _ Apple Factory

New mode

Factory A

Apples / oranges

Factory B

Apples / oranges

C factory

Apples / oranges

Teacher: "the complexity has changed from 6 to 3."

Xiaobai: "I understand, and I have learned something new."

Public interface IFruitFactory {Fruit CreateApple (string name); Fruit CreateOrange (string name);} public class AFactory: IFruitFactory {public Fruit CreateApple (string name) {return new Apple (name);} public Fruit CreateOrange (string name) {return new Orange (name);}}

Client implementation

IFruitFactory fac = new AFactory (); Fruit a_Apple = fac.CreateApple ("a factory"); Fruit a_Orange = fac.CreateOrange ("a factory"); a_Apple.PrintfName (); a_Orange.PrintfName (); IFruitFactory b_fac = new BFactory (); Fruit b_Apple = b_fac.CreateApple ("b factory") Fruit b_Orange = b_fac.CreateOrange ("b factory"); b_Apple.PrintfName (); b_Orange.PrintfName ()

Xiaobai: "but in what kind of scene to use this mode, I seem to have no idea."

Teacher: "the use of abstract factories is relatively small, but not without." Let me give you an example. At the beginning of the back end, we have various components [buttons, drawers, navigation bars] and so on. These components have corresponding skins, and the development of skins is the implementation of abstract factories. The factory interface is the definition of each component, and each skin is the implementation of a factory. If you want to switch skin, you just need to instantiate different factories. "

Xiaobai: "Oh. Is it the same as the skin switch in the game?"

Teacher: "you can also understand that the design pattern is just a general solution, which can be applied in different scenarios, and we can choose the scenario that suits us best and understands it best."

The bell rang again.

Teacher: "well, that's all for this class." next class we will talk about other design patterns. I hope you will listen on time. "

Advantages / disadvantages

Abstract factories deal with the concept of product families. In response to the concept of product family, it is easy to add new product lines, but it is not possible to add new products. For example, each car company may have to produce cars, vans and buses at the same time, then each factory should have the advantages of creating cars, vans and buses: providing an interface to the client without having to specify a specific product type. the disadvantage of creating product objects in multiple product families: adding a new product grade structure is complex Abstract factories and all concrete factory classes need to be modified to show skewed support for the "opening and closing principle"

Thank you for your reading. the above is the content of "how Xiaobai uses design patterns". After the study of this article, I believe you have a deeper understanding of how Xiaobai uses design patterns. The specific use of the situation also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report