C # design mode (2)--Simple Factory mode

Source: Internet
Author: User

Original address: http://www.cnblogs.com/zhili/p/SimpleFactory.html, Introduction

This series is also a few of their own design patterns of learning notes, hoping to some beginners design patterns of people to help, in the previous topic introduced a singleton model, in this topic continue to introduce a more easily understood mode-simple Factory mode.

Ii. Introduction to the Simple factory model

When it comes to simple factories, nature's first question is, of course, what is the simple factory model? In real life The factory is responsible for the production of products, also in the design mode, simple Factory mode We can also be understood as responsible for the production of the object of a class, in our usual programming, when using the "new" keyword to create an object, at this time the class is dependent on the object, That is, the coupling between them is high, when the demand changes, we have to modify this kind of source code, at this time we can use the object-oriented (OO) very important principles to solve this problem, the principle is- package changes, since the packaging changes, it is natural to find the change of code, Then we encapsulate the changed code in class , and this is the way our simple factory model is implemented. The following is a real-life example to elicit a simple factory model.

Work outside the people, inevitably to eat outside often, of course, we can also cook at home, but their own cooking and eating trouble, because they have to buy food, however, go out to eat completely without these troubles, we just have to go to the restaurant order can be, buy food things to the restaurant to do it, The restaurant serves as a simple factory, so let's see how real-life examples behave in code.

Self-cooking situation:

 <summary>///own cooking situation///without a simple factory, customers want to eat what food can only be fried by themselves////</summary> public class Customer {        <summary>///Cooking methods///</summary>/<param name= "type" ></param>             <returns></returns> public static food Cook (string type) {food food = null;            Customer A said: I want to eat tomato scrambled eggs how to do? Customer B said: "Then you burn it yourself//customer A said:" OK, then do it yourself if (type.            Equals ("Scrambled eggs with tomatoes") {food = new Tomatoscrambledeggs ();            }//I want to eat potato shredded pork, this still has to do//I feel good tired oh, if someone can help me do it? else if (type.            Equals ("shredded potato") {food = new shreddedporkwithpotatoes ();        } return food;            } static void Main (string[] args) {//Make tomato scrambled egg food food1 = Cook ("Tomato scrambled egg"); Food1.            Print ();            Food food2 = Cook ("shredded potatoes"); Food2.           Print (); Console.read ();        }}///<summary>///abstract class///</summary> public abstract class Food {//output point what dishes    public abstract void Print (); }///<summary>///tomato scrambled egg this dish////</summary> public class Tomatoscrambledeggs:food {p ublic override void Print () {Console.WriteLine ("A tomato scrambled egg!")        ");        }}///<summary>//Potato shredded pork////</summary> public class Shreddedporkwithpotatoes:food {        public override void Print () {Console.WriteLine ("One Piece of shredded potato"); }    }

Cooking, if we want to eat other dishes, we need to buy this kind of food and wash the tedious operation, with the restaurant (that is, the simple factory), we can take these operations to the restaurant to do, at this time the consumer (that is, we) on the food (that is, the specific object) of the dependence on the direct change from indirect, This is another principle of object-oriented- reducing the coupling between objects, the following is a concrete look at the implementation of the restaurant after the code (that is, the implementation of a simple factory):

<summary>///customer acting as client, responsible for invoking a simple factory to produce objects//customer order, Cook (equivalent to Simple factory) is responsible for cooking (the object of production)///</summary> class Cust Omer {static void Main (string[] args) {//customer want to order a tomato scrambled egg food food1 = Foodsi            Mplefactory.createfood ("Scrambled eggs with tomatoes"); Food1.            Print ();            Customers want to point a potato shredded meat food food2 = foodsimplefactory.createfood ("Potato shredded meat"); Food2.            Print ();        Console.read ();        }}///<summary>///abstract class///</summary> public abstract class Food {//output point what dishes    public abstract void Print (); }///<summary>///tomato scrambled egg this dish////</summary> public class Tomatoscrambledeggs:food {p ublic override void Print () {Console.WriteLine ("A tomato scrambled egg!")        ");        }}///<summary>//Potato shredded pork////</summary> public class Shreddedporkwithpotatoes:food { public override void Print () {ConsoLe.        WriteLine ("A piece of shredded potatoes"); }}///<summary>///Simple factory class, in charge of cooking///</summary> public class Foodsimplefactory {PU            Blic Static food Createfood (string type) {food food = null; if (type.            Equals ("shredded potatoes") {food= new shreddedporkwithpotatoes (); } else if (type.            Equals ("Scrambled eggs with tomatoes") {food= new Tomatoscrambledeggs ();        } return food; }    }
Third, advantages and disadvantages

After watching the implementation of the simple factory model, you and your friends will certainly have this kind of confusion (because I also have the time of study)-so we just moved the changes to the factory class, as if there is no change in the problem, because if the customer wants to eat other dishes, at this time we still need to modify the factory class method (that is, the client class is modified before the simple Factory mode is applied). The first thing I want to say is, you and your little buddy are right, this is the downside of the Simple factory model (the factory method described later in this shortcoming can be well solved), however, the simple factory pattern and the previous implementation also have its advantages:

    • Simple Factory mode solves the problem that the client is directly dependent on the specific object, and the client can eliminate the responsibility of directly creating the object, but only the consumer product. The simple factory model realizes the division of responsibility.
    • The simple factory model also played the role of code reuse, because the previous implementation (the case of their own cooking), a person also to go in their own class to implement the method of cooking, and then have a simple factory, to eat in the restaurant everyone is not so troublesome, just to be responsible for consumption. At this point, the simple factory cooking method has been shared with all customers. (This is also a disadvantage of the simple factory approach – because the factory class centralizes all the product creation logic, and once it doesn't work, the whole system is affected, and there's nothing to understand, as things have two sides .)

Although the disadvantages of the simple factory model are described above, here is a summary of the drawbacks of the Simple factory model:

    • The factory class centralizes all product creation logic, and once it does not work, the entire system is affected (in layman's words: Once a restaurant is out of food or closed, many people who are unwilling to cook have no food to eat)
    • System expansion is difficult, and once you add a new product you have to modify the factory logic, which makes the factory logic too complex.

After understanding the pros and cons of the simple factory model, we can then know the application scenario for a simple factory:

    • When the factory class is responsible for creating fewer objects, consider using simple Factory mode ()
    • Customers can consider using simple Factory mode if they only know the parameters of the incoming factory class and don't care about how to create the object's logic
Four, simple Factory mode UML diagram

The simple factory model is also called the static method pattern (because the factory class defines a static method), and a factory class creates an instance of the product class based on the parameters passed in (popular point expression: The customer is responsible for burning the dish through orders). The UML diagram for simple Factory mode is as follows:

Five. The implementation of simple Factory mode in net

After introducing the simple factory model, I studied like this:. NET class Library is there a class that implements the simple factory pattern? There is indeed, the following. The System.Text.Encoding class in net implements the simple factory pattern, in which the getencoding (int codepage) is the factory method , The specific code can be viewed through the Reflector Anti-compilation tool, and I'll post some of the code in the method below:

public static Encoding getencoding (int codepage) {Encoding unicode = null;    if (encodings! = null) {Unicode = (Encoding) encodings[codepage];        } if (unicode = = null) {object obj2;        BOOL LockTaken = false;            try {monitor.enter (obj2 = internalsyncobject, ref LockTaken);            if (encodings = = null) {encodings = new Hashtable ();            } Unicode = (Encoding) encodings[codepage];            if (Unicode = null) {return unicode;                    } switch (codepage) {case 0:unicode = Default;                Break Case 1:case 2:case 3:case 0x2a:throw New ARGUMENTEXCEP                tion (environment.getresourcestring ("argument_codepagenotsupported", new object[] {codepage}), "codepage"); Case 0x4b0:unIcode = Unicode;                Break                    Case 0x4b1:unicode = Bigendianunicode;                Break                    Case 0x6faf:unicode = Latin1;                Break                    Case 0xfde9:unicode = UTF8;                Break                    Case 0x4e4:unicode = new sbcscodepageencoding (codepage);                Break                    Case 0x4e9f:unicode = ASCII;                Break                    Default:unicode = Getencodingcodepage (codepage);                    if (Unicode = = null) {Unicode = Getencodingrare (codepage);            } break; } encodings.            ADD (codepage, Unicode);        return Unicode;     }}

The UML diagrams for encoding in. NET are:

The simple factory pattern implemented in the Encoding class is an evolution of the simple factory model, when simple factory classes are played by abstract product roles, however. How does the encoding class in the net solve the problems in the simple factory model (i.e. what if a new encoding is added)? The switch function in the GetEncoding method has the following code:

Switch (codepage)     {          ...   .. Default:                    Unicode = Getencodingcodepage (codepage);                    if (Unicode = = null)                    {                        getencodingrare(codepage);//When code is seldom seen                    } break                    ;           ......      }

In the Getencodingrare method, there are some infrequently coded instantiation code, Microsoft formally through this method to solve the problem of adding a new encoding. (In fact, it is a list of all possible coding scenarios), Microsoft in this way to solve this problem, it may be because the code is now stable, the possibility of adding new encodings is relatively low, so in. NET 4.5 still did not change this part of the code.

Vi. Summary

Here, the introduction to the Simple factory model is here, and the factory method pattern is introduced later to solve the problems in the simple factory model.

C # design mode (2)-Simple Factory mode

Related Article

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.