C # design model (2) -- simple factory Model

Source: Internet
Author: User

I. Introduction

This series also provides some learning notes for the design model. I hope it will be helpful to some beginners. I introduced the singleton model in the previous topic, in this topic, we will continue to introduce a simple factory model that is easier to understand.

II. Introduction to the simple factory Model

Speaking of simple factories, naturally, the first question is, of course, what is a simple factory model? In real life, the factory is responsible for the production of products. In the same design model, we can also be understood as responsible for the simple factory model.A class of the production object,In normal programming, when an object is created using the "new" keyword, this class is dependent on this object, that is, the coupling between them is high. When the demand changes, we have to modify the source code of this class. At this time, we can use the very important principle of object-oriented (OO) to solve this problem. This principle is: encapsulate changes, to encapsulate changes, you need to find the changed code and then encapsulate the changed code with classes.This is the implementation method of our simple factory model. The following uses an example in real life to introduce a simple factory model.

If you work outside, you may have to eat out frequently. Of course, you can also cook at home, but it is troublesome to cook, because you have to buy food by yourself. However, there is no such trouble when we go out for dinner. We only need to order food at the restaurant. We can buy food at the restaurant. Here, the restaurant serves as a simple factory, let's take a look at how code is used in real life examples.

Self-cooking:

                                                  Food Cook(=              (type.Equals(=               (type.Equals(=   Main(            Food food1 = Cook(= Cook(                                                

If we want to eat other dishes by ourselves, we need to buy such dishes and wash dishes. After having a restaurant (that is, a simple factory, we can hand over these operations to restaurants. At this time, the dependency between consumers (that is, We) on food (that is, the specific object) has changed from direct to indirect, in this way, another object-oriented principle is implemented --Next, let's take a look at the implementation code (that is, the implementation of a simple factory) with the restaurant ):

            Main(            Food food1 = FoodSimpleFactory.CreateFood(            Food food2 = FoodSimpleFactory.CreateFood(                                                             Food CreateFood(=  (type.Equals(=   (type.Equals(= 
Iii. Advantages and Disadvantages

After reading the implementation of the simple factory model, you and your friends will certainly have such doubts (because I also learned) -- in this way, we just moved the changes to the factory class. It seems that there is no change, because if the customer wants to eat other dishes, we(That is, add case statements. Before the simple factory mode is applied, the customer class is modified ). First, I would like to say: You and your friends are right,This is the disadvantage of the simple factory model.(The Factory method described later in this article can be well solved). However, the simple factory model and the previous implementation also have its advantages:

  • The simple factory mode solves the problem that the client directly depends on specific objects. The client can eliminate the responsibility for directly creating objects, instead of consuming products. The simple factory model separates responsibility.
  • The simple factory mode also plays a role in code reuse, because in the previous implementation (self-cooking), another person also needs to implement the cooking method in his class, then, with a simple factory, everyone who goes to a restaurant does not need to be so troublesome. They only need to be responsible for consumption. At this time, the simple factory cooking method will be shared by all customers. (At the same time, this is also a disadvantage of the simple factory method-because the factory class focuses on the Creation logic of all products, once the operation fails, the entire system will be affected, and there is nothing hard to understand, just likeEverything has two sides.)

Although the shortcomings of the simple factory model have been introduced above, the shortcomings of the simple factory model are summarized below:

  • The factory class focuses on the Creation logic of all products. Once it fails to work normally, the entire system will be affected (generally, once a restaurant has no meals or is closed, A lot of people who don't want to cook don't eat)
  • It is difficult to expand the system. Once a new product is added, the factory logic has to be modified. This will make the factory logic too complex.

After understanding the advantages and disadvantages of the simple factory model, we can then understand the application scenarios of the simple factory:

  • When the factory class is responsible for creating fewer objects, you can consider using the simple factory mode ()
  • If you only know the parameters passed into the factory class, you can consider using the simple factory mode when you do not care about how to create the object logic.
4. Simple factory mode UML diagram

Simple factory mode is also called static method mode (because factory Classes define a static method ), A factory class determines which product class instance is created based on the input parameters (popular expression: the food is burned by the order placed by the customer ). The UML diagram of the simple factory mode is as follows:

V. Implementation of simple factory mode in. NET

After introducing the simple factory model, I learned how to implement the simple factory model in the. NET class library? In. NET, the System. Text. Encoding class implements the simple factory mode.GetEncoding (int codepage)Is the factory Method,The specific code can be viewed through Reflector decompilation tool. I will also post some code in this method:

Encoding GetEncoding (= (encodings! ==( Unicode = lockTaken = InternalSyncObject, (encodings === (unicode! = ArgumentException (Environment. GetResourceString (, [] {codepage}), ======= (unicode ===View Code

The UML diagram of Encoding in. NET is:

EncodingThe simple factory model implemented in the class is an evolution of the simple factory model. At this time, the simple factory class is played by the abstract Product role, however. in NET, how does the Encoding class solve the problems in the simple factory mode (that is, what if a new Encoding is added )? The switch function in the GetEncoding method has the following code:

 = (unicode == = (codepage); 

The GetEncodingRare method contains some instantiated code that is not commonly used for encoding. Microsoft officially uses this method to solve the problem of adding a new encoding. (In fact, listing all possible encoding situations). The reason why Microsoft solves this problem in this way may be that the encoding is now stable and the possibility of adding new encoding is relatively low, so in. NET 4.5 still does not change this part of the code.

Vi. Summary

Here, the introduction of the simple factory model is here, and the factory method mode will be introduced later to solve the problems in the simple factory model.

All source code in this topic: simple factory mode source code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.