Primary design mode-Simple factory

Source: Internet
Author: User

As a novice who has just started. Although only to learn a little of the fur of programming language (or even the fur is not), but with time and study in depth, "design pattern" This term is slowly emerging in the eyes.

What is design mode? How will it help us to emerge? ...... And so on, a series of questions will appear in our minds. As the saying goes: The problem is the key to explore knowledge. Let's take

Learn design patterns together with your own questions.

First, let's start by understanding what design patterns are and the advantages of using design patterns.

A simple understanding of design patterns: A pattern is a solution to a problem in a certain context.
1. Reuse solution-by reusing an already recognized design, I can get a first-advantage in solving problems and avoid repeating the mistakes of previous generations. I can benefit from learning from the experience of others and don't need to design a solution for a problem that always repeats itself.
2. Establish common terminology-communication and collaboration in development requires a common vocabulary base and consensus on issues. Design patterns provide a common benchmark in the analysis and design phases of a project.
3. Improve the observation height--The pattern also provides us with a higher level of view of the problem of observation, design process and object-oriented, which frees us from the shackles of "premature handling of details".
4. Most design patterns also make the software easier to modify and maintain. The reason for this is that they are all proven solutions. As a result, their structure has been developed over the long term and is more adept at coping with change than a newly conceived solution. Also, the code used by these patterns tends to be easier to understand-making the code easier to maintain.

In this case, the design pattern can be seen as a general term for a solution that solves a problem in a relative way.

There are 23 types of design patterns, of which five are often used in development, I believe we have heard earlier, I am not more verbose, the following into the topic: Design mode-Simple factory.

We will take a simple example to learn about a simple factory.

Multi-State Calculator

Enter two number and select any algorithm to calculate two number of results.

We first solve the problem in polymorphic way:

1. Creation of classes

2. Key code

1Operation operation =Newoperation ();2                 Switch(CmbCountWay.SelectedItem.ToString (). Trim ())3                 {4                      Case "+":5Operation =NewOperationadd ();6                          Break;7                      Case "-":8Operation =Newoperationsubtraction ();9                          Break;Ten                      Case "*": OneOperation =Newoperationmultiplication (); A                          Break; -                      Case "/": -Operation =Newoperationdivision (); the                          Break; -                     default: -                          Break; -                 } +                 //to calculate -Operation. Firstnum =Double. Parse (TxtFirstNum.Text.Trim ()); +Operation. Secondnum =Double. Parse (TxtSecondNum.Text.Trim ()); A                 Doubleresult =operation. GetCount (); at                  This. Txtresult.text = result. ToString ();
View Code

Through the code we will find:

When we are programming, this object relies on this class whenever "new" is an object. If you need to modify this class for some reason during the later maintenance process, the only way to do this is to open the source code, modify it, and modify all the operations associated with the object. This is very bad for us.
The problem is: objects cannot respond to changes in "concrete instantiation types"
Solution: Package change point, where changes, packaging where. In this example, the class to instantiate is changed, and the instantiation of the operation is encapsulated, and we can transfer the "new" operation to a specific class, which is responsible for creating an instance of the concrete class based on our condition, which is the "Simple Factory mode" below.

Simply add a factory class and generate the calculation method by passing the calculated symbols.

  Public classOperatorfactory { Public StaticOperator Creatoperator (stringOper) {Operator Calc=NULL; Switch(oper) { Case"+": Calc=NewAdd ();  Break;  Case"-": Calc=NewSum ();  Break;  Case"*": Calc=NewMul ();  Break;  Case"/": Calc=NewDiv ();  Break; }            returnCalc; }    }
operatorfactory
 Private voidBtncount_click (Objectsender, EventArgs e) {            intNumleft =Convert.ToInt32 (Txtnumleft.text); intNumright =Convert.ToInt32 (Txtnumright.text); stringOper =cmbOperator.SelectedItem.ToString (); Operator Calc=Operatorfactory.creatoperator (OPER); Try{Calc. Numleft=Numleft; Calc. Numright=Numright; Txtresult.text=Calc. Operation ().            ToString (); }            Catch(Exception ex) {MessageBox.Show (ex).            Message); }        }
Main ()

From the above code comparison, we are not difficult to see:

(Simple Factory) Advantages:

    • The simple factory model is able to determine which specific class of objects should be created based on the information given by the outside world. Through it, outsiders can get out of the awkward situation of directly creating specific product objects.
    • The outside is isolated from the specific class, the coupling is low.
    • Clearly distinguishes the respective responsibility and the power, facilitates the entire software system structure optimization.

Disadvantages:

    • Although the simple factory model can adapt to certain changes, the problem it solves is far from limited. The classes it can create can only be taught in advance, and if you need to add new classes, you need to change the factory class. (How to make a further optimization improvement I need to continue to learn)

Application Scenarios

    • The factory class is responsible for creating fewer objects
    • The customer only knows the parameters that passed into the factory class and does not care about how to create the object (logic)

The Art of war has 36 ... 36 is a summary of the past years of outstanding military strategist experience, in order to facilitate future generations to learn the art of war ... On the understanding of their God eclectic can become the art of war, the use of the proper mastery of the general, the next only know the form according to the rules can be taken to bluff people ...

Wushu has a routine ... The routine is a summary of the actual combat experience of the predecessors, will be a series of offensive and defensive commonly used moves to facilitate the record of posterity, drill ... On the understanding of their God eclectic can become martial arts, the use of mastery in the right can become a master, the next only know the form according to the rules can be taken to bluff people ...

Design mode is a summary of the previous experience in the development of programming experts, in order to facilitate future generations to learn ... On the understanding of their God eclectic can become the legendary Daniel, the use of the proper mastery of the well-paid, the next person only know the form of compliance according to the rules can be taken to bluff people ...

Only from the books to go to school, only listen to other people's discussion but not in the actual practice of their own to understand can only be done to bluff people ... (so suggest to use, slowly smell)

If you learn in the actual combat can not see what the benefits of nothing to come out to bluff people ...

Primary design mode-Simple factory

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.