Design pattern Strategy Mode & Simple Factory mode _ design mode

Source: Internet
Author: User

Learning design patterns have been a long time, in fact, has been knocked over once, but the old feel that nothing has been learned, not enough understanding, and now take advantage of the reconfiguration of the computer room, and then again, it is not too late.

In fact, after knocking on the computer room, look at the mode, in fact, it was difficult to understand, it is difficult to read the code a glance can be read, while a little feeling, early harvest it. Simple Factory mode:

Simple factory Model: Easy to change, you can use the Simple factory model. Instance:

For example: We are shopping malls, just shopping malls promotions, a variety of promotional activities: 300 return to 100, there are 80 percent, draw and so on.

In terms of promotions, various promotional activities are actually changes.

Another example: When we buy breakfast, the breakfast shop is dazzling, but no matter who comes to the store to buy all the department, the salesperson asked you what you need, he will know what to bring you something.   What we need is change. On

A simple factory pattern is an instance of a class that returns several possible classes of macros through incoming data.   But these types generally have a common feature: these kinds have a common parent class and a common method, but each method is different and optimized according to different data. Depth:

The above is talking about, essence: In the face of these changes, object-oriented thinking is to encapsulate these changes, encapsulation changes, you can increase its scalability, no longer modify the previous class. Simple factory pattern Structure diagram:


To achieve shopping malls promotion:

Parent class:

<span style= "Background-color:rgb (204, 204, 204);" ><strong> abstract    Class cashsuper//parent class, an abstraction or, encapsulating
    {public
        abstract double Acceptcash (double money);
    } </strong></span>

Each subclass:

    Class cashnormal:cashsuper//Each instantiated object, implements the polymorphic {public override double Acceptcash (double)/the method in the parent class, and
        There are differences between different classes {return money;
        } class Cashrebate:cashsuper {private double moneyrebate = 1d; Public cashrebate (String moneyrebate) {this.moneyrebate = double.
        Parse (moneyrebate);
        Override double Acceptcash (double) {return money * moneyrebate;
        } class Cashreturn:cashsuper {private double moneycondition = 0.0d;
        Private double moneyreturn = 0.0d; Public Cashreturn (String moneycondition,string moneyreturn) {this.moneycondition = double.
            Parse (moneycondition); This.moneyreturn = Double.
        Parse (Moneyreturn);
            Override double Acceptcash (double) {double = money;
        if (Money >= moneycondition)        result = Money-math.floor (money/moneycondition) * Moneyreturn;
        return result; }

    }

Factory mode:

    Simple Factory mode
    class cashfactory//simple Factory mode, which puts the selection on the business layer, not the interface layer
    {public
        static Cashsuper createcashaccept ( String type)
        {
            Cashsuper cs = null;//defines a type switch (type) for a parent class
            {case
                "normal charge":
                    cs = new Cashnormal ();//instantiated is the break of each subclass object
                    ;
                Case "Full 300":
                    cashreturn CR1 = new Cashreturn (",");
                    break;
                Case "Dozen 80 percent":
                    cashrebate Cr2 = new Cashrebate ("0.8");
                    break;
            return CS;
        }
    

Interface layer:

        private void Button1_Click (object sender, EventArgs e)
        {
            // Simple Factory model-------------------------------------------------------------------
            Cashsuper csuper = Cashfactory.createcashaccept (cbxType.SelectedItem.ToString ())//Simple Factory mode, the client knows two classes, Cashsuper and Cashfactory, The simple factory model has already instantiated each subclass object
            double totalprices = 0d;
            Totalprices = Csuper.acceptcash (convert.todouble (txtprice.text) * convert.todouble (Txtnum.text));
            Total = Total + totalprices;
            LBXLIST.ITEMS.ADD ("unit Price" + Txtprice.text + "Quantity:" + Txtnum.text + "" + Cbxtype.selecteditem + "total:" + totalprices.tostring ()) ;
            Label4. Text = total. ToString ();

        }

As we all know, stores don't always have promotions, also not necessarily this year this kind of promotion, next year or this, things are changing over time, if each change of discount amount and rebate amount, every time to maintain or expand the charging method, must change the factory, has been code Xu recompile deployment, it would be very bad, In the face of the market changes in the algorithm, we need a strategy model.

Policy mode:

Example: in-store promotions need to change the discount amount and rebate amount each year.

Structure Chart:


Chat:

In fact, the strategy model defines the algorithm family, packaged separately, so that they can replace each other, this mode so that the changes in the algorithm, will not affect the use of algorithm customers.   All of these algorithms do the same work, but only implement different, he can invoke all the algorithms in the same way, reduce the coupling between the algorithm class and the use algorithm class. Depth:

Simple factory to generate algorithm objects, the algorithm is always possible to replace each other, this is the change point, packaging change point. Implement Store Promotions:

The preceding parent class and promotion subclass do not need to be modified:

Policy Mode code:

    Class cashcontext//is configured with a cashcontext to maintain a reference to the Strategy object.
    {
        cashsuper cs=null;
        The public Cashcontext (string type)//applies a simple factory pattern to instantiate objects (different subclasses)
        {
            switch (type)//to a value to select different objects, passing in the specific policy object
            { Case
                "normal charge":
                    Cashnormal cs0=new cashnormal ();
                    Cs=cs0;
                    break;
                Case "Full 300":
                    cashreturn cr1=new Cashreturn (",");
                    CS=CR1;
                    break;
                Case "Dozen 80 percent":
                    cashrebate cr2=new cashrebate ("0.8");
                    CS=CR2;
                    break;
            }
        }
        Public double GetResult (double)
        {return
            Cs.acceptcash (money);
        }
    }

Interface code:

        private void Button1_Click (object sender, EventArgs e)
        {


            // The combination of policy patterns and simple factory patterns----------------------------------------------------
            cashcontext csuper = new Cashcontext ( CbxType.SelectedItem.ToString ())//client only know cashcontext on line, pure as the specific policy object
            double totalprices = 0d;
            Totalprices = Csuper. GetResult (convert.todouble (txtprice.text) * convert.todouble (Txtnum.text));
            Total = Total + totalprices;
            LBXLIST.ITEMS.ADD ("Price:" + Txtprice.text + "Quantity:" + Txtnum.text + "" + Cbxtype.selecteditem + "total:" + totalprices. ToString ());
            Label4. Text = total. ToString ();
        }

These are the combination of the strategic model and the simple factory model, and the simple factory model is simply: the process of creating an instance of a class. Policy patterns: Policies can be replaced at any time.


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.