Design Pattern-Rule Pattern

Source: Internet
Author: User
ArticleDirectory
    • What is policy mode?
    • Structure of Rule Mode
    • Advantages and disadvantages of Rule Mode
    • Code instance in Rule Mode
    • Differences between policy modes and simple factories
What is policy mode?

Strategy pattern: definedAlgorithmFamily, respectively encapsulated, so that they can replace each other. This pattern changes the algorithm and does not affect the customers who use the algorithm.

Policy mode is a method that defines a series of algorithms. From a conceptual point of view, all these algorithms perform the same job, but they only implement differently, it can call all algorithms in the same way, reducing the coupling between various algorithm classes and algorithm classes.

Structure of Rule Mode

First, observe the policy mode (Strategy Pattern:

Based on the class diagram above, we can know that the policy mode consists of the following parts:

    • Abstract strategy: Therefore, the general interface of the Policy subclass is usually implemented by an abstract class and interface.
    • Specific strategies: Implements the abstract policy class, packaging related algorithms and behavior.
    • Context class: For customersCodeCall, holding a reference to the abstract policy class. Different policy instances are returned based on different client calls.

 

Advantages and disadvantages of Rule Mode

Advantages of the Policy mode:

    • It provides an alternative to inheritance, and maintains the advantages of inheritance (code reuse) and is more flexible than inheritance (algorithms are independent and can be expanded at will ).
    • The strategy class hierarchy of the Policy mode defines a series of reusable algorithms or actions for context. Inheritance helps to analyze the common functions of these algorithms.
    • When different behaviors are stacked in a class, it is difficult to avoid using conditional statements to select appropriate behaviors. Encapsulate these behaviors in independent strategy classes, and then use these behavior classes to eliminate conditional statements.
    • Comply with most grasp principles and common design principles, high cohesion and low coupling.
    • Policy mode simplifies unit testing because each algorithm has its own class and can be tested independently through its own interface.

Disadvantages of Rule mode:

    • Because each specific policy class generates a new class, the number of classes to be maintained by the system is increased.
    • When combined with a simple factory, you also need to modify the switch branch statement.

 

Code instance in Rule Mode

Based on discounts and promotions in malls, algorithms need to be constantly changed to provide a billing method.Program.

 First define a settlement abstract class (Interface ):

 1       ///   <Summary>  2       ///  Cash charge abstract class  3       ///   </Summary>  4       Abstract  Class  Cashsuper  5   {  6           //  The abstract method of the cash receipt class. The cash is collected. The parameter is the original price and the current price is returned.  7           Public   Abstract   Double Acceptcash ( Double  Money );  8 }

 

Subcategory of the specific billing Function Based on discounts, promotions, and other activities

1       ///   <Summary>  2       ///  Normal billing subclass  3       ///   </Summary>  4       Class  Cashnormal: cashsuper  5   {  6           Public   Override  Double Acceptcash ( Double  Money)  7   {  8               Return  Money;  9   }  10   }  11   12       ///   <Summary>  13      ///  Discount subclass  14       ///   </Summary>  15       Class  Cashrebate: cashsuper  16   {  17           Private   Double Moneyrebate = 1D;  18           Public Cashrebate (String  Moneyrebate)  19   {  20               This . Moneyrebate = Double  . Parse (moneyrebate );  21   }  22   23           Public   Override   Double Acceptcash ( Double Money)  24   {  25               Return Money * Moneyrebate;  26   }  27   }  28   29       ///   <Summary>  30       ///  Rebate subclass 31       ///   </Summary>  32       Class  Cashreturn: cashsuper  33   {  34           Private   Double Moneycondition = 0.0d  ;  35           Private   Double Moneyreturn =0.0d  ;  36   37           ///   <Summary>  38           ///  Rebate subclass Construction Method  39           ///   </Summary>  40           ///   <Param name = "moneycondition">  Rebate criteria  </Param> 41           ///   <Param name = "moneyreturn">  Rebate Value  </Param>  42           Public Cashreturn ( String Moneycondition, String  Moneyreturn)  43   {  44               This . Moneycondition = Double . Parse (moneycondition );  45               This . Moneyreturn = Double  . Parse (moneyreturn );  46   }  47   48           Public   Override   Double Acceptcash ( Double  Money)  49   { 50               Double Result = Money;  51   52               If (Money> = Moneycondition)  53 Result = money-math. Floor (money/moneycondition )* Moneyreturn;  54   55               Return  Result;  56   } 57 }

 

The last created is the context class provided to the client for calling.

 1    Class  Cashcontext  2   {  3   Cashsuper Cs;  4   5           Public Cashcontext ( String  Type)  6  {  7               //  Simple factory constructor to overcome the disadvantages of sub-classes of algorithms that the client needs to know (encapsulates changes)  8               Switch  (Type)  9   {  10                   Case   "  Normal charges  "  :  11 Cs =New  Cashnormal ();  12                       Break  ;  13                   Case   "  300 to 100  "  :  14 Cs = New Cashreturn ( "  300  " ,"  100  "  );  15                       Break  ;  16                   Case   "  Off  "  :  17 Cs = New Cashrebate ( "  0.8 "  );  18                       Break  ;  19   }  20   }  21   22           //  What's different from a simple factory?  23           Public   Double Getresult ( Double Money)  24   {  25               Return  CS. acceptcash (money );  26   }  27 }

In the Basic Policy mode, the responsibility for selecting the specific implementation is borne by the client object and transferred to the context object in the Policy mode. This does not relieve the pressure on the client to determine the selection. After the policy mode is combined with a simple factory, the responsibility for selecting a specific implementation can also be borne by the context, this minimizes the client's responsibilities.

 

Call customer code, compile and run:

 1 Cashcontext csuper = New Cashcontext (cmbdiscount. selecteditem. tostring ());  2               Double Totalprices = 0d;  3 Totalprices = csuper. getresult ( Double . Parse ( This . Txtprice. Text )* Double . Parse ( This  . Txtnumber. Text ));  4   5               This . Lbxresult. Items. Add ("  Unit price:  " + This . Txtprice. Text + "  Quantity:  " + This . Txtnumber. Text + "   " + Cmbdiscount. selecteditem + "   " + "  Total  " +Totalprices. tostring ());  6   7 Total = total + Totalprices;  8               This . Lblamount. Text = total. tostring ();

Differences between policy modes and simple factories

ComparisonSimple FactoryCompared with the UML class diagram of the Policy mode, we can find that the structure of the two is similar:

We can find that all implementations implemented using the rule mode can be implemented using a simple factory, both of which are implemented by using inheritance in the form of polymorphism. It is appropriate to use the policy mode when the product structure overlaps multiple times and different rules (algorithms) are applied at different times. We can find that a simple factory only uses a static class method to create different subclasses, but in the Policy mode, apart from creating different algorithm subclasses through polymorphism, there is also a Member method that calls the subclass example function (in the context class), so in the client we only need to obtain a context instance, then, call its instance method directly to indirectly call the member method of the subclass (constructor is implemented using a simple factory ); however, in a simple factory, in addition to calling the static method of the factory class to obtain the instance of the product subclass, we also need to directly call the member method of the subclass.

 

Download with a click: Sample Code

References: big talk Design Model

author: sunny pig

Source: http://www.cnblogs.com/IPrograming

the copyright of this article is shared by the author and the blog. You are welcome to repost it. However, you must keep this statement without the author's consent and provide a connection to the original article on the article page, otherwise, you are entitled to pursue legal liability.

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.