Rule mode of Java and Mode

Source: Internet
Author: User
ArticleDirectory
    • Source code
    • Source code

Dr. Yan Hong's book "Java and patterns" describes the strategy pattern in this way:

The rule mode is the behavior mode of the object. Intended for a groupAlgorithm, Encapsulate each algorithm into an independent class with a common interface, so that they can be replaced with each other. The policy mode allows the algorithm to change without affecting the client.

Structure of Rule Mode

Policy mode encapsulates algorithms and separates the responsibility for using algorithms from the algorithms themselves and delegates them to different objects for management. Rule mode typically packs a series of algorithms into a series of policy classes and serves as a subclass of an abstract policy class. In one sentence, it is: "prepare a group of algorithms and encapsulate each algorithm to make them interchangeable ". The following describes the structure of the Policy mode instance with a schematic implementation.

This mode involves three roles:

Environment (context) role:Hold a reference of strategy.

Abstract Policy (Strategy) role:This is an abstract role, usually implemented by an interface or abstract class. This role provides all the interfaces required for specific policy classes.

Concretestrategy role:Related algorithms or behaviors are encapsulated.

Source code

Environment

 Public   Class  Context {  //  Object holding a specific policy      Private  Strategy strategy;  /**  * Constructor: input a specific policy object *  @ Param  Strategy specific policy object  */      Public  Context (strategy Strategy ){ This . Strategy = Strategy ;}  /**  * Policy Method  */      Public   Void  Contextinterface () {strategy. strategyinterface ();}} 

Abstract strategy

Public InterfaceStrategy {/*** Policy Method*/Public VoidStrategyinterface ();}

Specific strategies

 
Public ClassConcretestrategyaImplementsStrategy {@ overridePublic VoidStrategyinterface (){//Related Services}}
  Public   class  concretestrategyb  implements   Strategy {@ override   Public   void   strategyinterface () { ///   related services  }} 
Public ClassConcretestrategycImplementsStrategy {@ overridePublic VoidStrategyinterface (){//Related Services}}

Use Cases

Suppose we want to design a shopping cart system for e-commerce websites selling books. The simplest case is to multiply the unit price of all goods by the quantity, but the actual situation must be more complicated than that. For example, this website may offer a 20% discount to all senior members, a 10% discount to intermediate members, and no discount to junior members.

According to the description, the discount is based on one of the following algorithms:

Algorithm 1: There is no discount for junior members.

Algorithm 2: provides a 10% discount to intermediate members.

Algorithm 3: provides a 20% discount to senior members.

The structure chart implemented using the Policy mode is as follows:

Source Code

Abstract discount

 
Public InterfaceMemberstrategy {/*** Calculate the book price *@ ParamThe original price of booksprice *@ ReturnCalculate the discount price*/Public DoubleCalcprice (DoubleBooksprice );}

Discount for junior members

Public ClassPrimarymemberstrategyImplementsMemberstrategy {@ overridePublic DoubleCalcprice (DoubleBooksprice) {system. Out. println ("No discounts for junior members");ReturnBooksprice ;}}

Intermediate member discount

Public ClassIntermediatememberstrategyImplementsMemberstrategy {@ overridePublic DoubleCalcprice (DoubleBooksprice) {system. Out. println ("The discount for intermediate members is 10%");ReturnBooksprice x 0.9;}}

Discount for senior members

Public ClassAdvancedmemberstrategyImplementsMemberstrategy {@ overridePublic DoubleCalcprice (DoubleBooksprice) {system. Out. println ("The discount for senior members is 20%");ReturnBooksprice x 0.8;}}

Price

 Public   Class  Price {  //  Hold a specific policy object     Private  Memberstrategy strategy;  /**  * Constructor: input a specific policy object *  @ Param  Specific policy objects of Strategy  */      Public  Price (memberstrategy Strategy ){  This . Strategy = Strategy ;}  /**  * Calculate the book price *  @ Param The original price of booksprice *  @ Return  Calculate the discount price  */      Public   Double Quote ( Double  Booksprice ){  Return   This  . Strategy. calcprice (booksprice );}} 

Client

 Public   Class  Client {  Public  Static   Void  Main (string [] ARGs ){  //  Select and create the policy object to be used Memberstrategy strategy = New  Advancedmemberstrategy ();  //  Create Environment Price = New  Price (Strategy );  //  Price Calculation          Double Quote = Price. Quote (300); System. Out. println ( "The final price of books is:" + Quote );}} 

From the above example, we can see that the policy mode only encapsulates algorithms, and provides new algorithms to be inserted into existing systems, as well as the old algorithms to "retire" from the system, the policy mode does not determine when to use the algorithm. Under what circumstances is the algorithm used determined by the client.

Recognition policy Mode

Center of gravity of policy Mode

The focus of the policy mode is not how to implement algorithms, but how to organize and call these algorithms to makeProgramThe structure is more flexible, with better maintainability and scalability.

Equality of Algorithms

A major feature of the policy model is the equality of each policy algorithm. For a series of specific policy algorithms, everyone has the same status. Because of this equality, algorithms can be replaced with each other. All policy algorithms are independent of each other and are independent from each other.

So we can describe this series of policy algorithms as follows: Policy algorithms are different implementations of the same behavior.

Uniqueness of runtime policies

During running, the policy mode can only use one specific policy to implement objects at a time. Although you can dynamically switch between different policy implementations, you can only use one.

Public Behavior

It is often seen that all specific policy classes have some public behaviors. At this time, these public behaviors should be put into the strategy class of the common abstract policy role. Of course, at this time, the abstract policy role must be implemented using a Java Abstract class, rather than an interface.

In fact, this is also a typical standard practice of inheriting code to the top of the hierarchy.

 

Advantages of Rule Mode

(1) The policy mode provides methods for managing related algorithm families. The hierarchical structure of a policy class defines an algorithm or behavior family. Proper use of inheritance allows you to move public code to the parent class to avoid code duplication.

(2) using policy mode can avoid using multi-condition (if-else) statements. Multi-condition statements are not easy to maintain. they mix the logic of which algorithm or behavior is adopted with the logic of the algorithm or behavior and are all listed in a multi-Condition Statement, it is more primitive and backward than the inheritance method.

Disadvantages of Rule Mode

(1) The client must know all the policy classes and decide which one to use. This means that the client must understand the differences between these algorithms so that appropriate algorithm classes can be selected in a timely manner. In other words, the policy mode is only applicable when the client knows the algorithm or behavior.

(2) because the policy mode encapsulates each specific policy implementation into a class separately, if there are many alternative policies, the number of objects will be considerable.

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.