Java and pattern 26-16th-Rule Pattern

Source: Internet
Author: User
ArticleDirectory
    • Source code

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.

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

 
Package COM. bankht. strategy;/*** @ Author: -AK47 * @ Creation Time: 10:16:58, December 26, ** @ Class description: abstract discount class */public interface memberstrategy {/*** calculate the book price ** @ Param booksprice * original book price * @ return calculate the discount price */Public double calcprice (double booksprice );}

Discount for junior members

Package COM. bankht. strategy;/*** @ Author: -AK47 * @ Creation Time: 10:17:28, December 26, ** @ Class description: discount class for junior members */public class primarymemberstrategy implements memberstrategy {@ overridepublic double calcprice (double booksprice) {system. out. println ("No discounts for junior members"); Return booksprice ;}}

 

Intermediate member discount

 
Package COM. bankht. strategy;/*** @ Author: -AK47 * @ Creation Time: 10:18:15, December 26, ** @ Class description: intermediate member discount class */public class intermediatememberstrategy implements memberstrategy {@ overridepublic double calcprice (double booksprice) {system. out. println ("10% discount for intermediate members"); Return booksprice * 0.9 ;}}

 

Discount for senior members

Package COM. bankht. strategy;/*** @ Author: -AK47 * @ Creation Time: 10:18:59, December 26, ** @ Class description: advanced member discount class */public class advancedmemberstrategy implements memberstrategy {@ overridepublic double calcprice (double booksprice) {system. out. println ("20% discount for senior members"); Return booksprice * 0.8 ;}}

 

Price

 
Package COM. bankht. strategy;/*** @ Author: -AK47 * @ Creation Time: 10:19:22, December 26, ** @ Class description: price class */public class price {// holds a specific policy object private memberstrategy strategy;/*** constructor, input a specific policy object ** @ Param strategy * specific policy object */Public price (memberstrategy Strategy) {This. strategy = strategy;}/*** calculate the book price ** @ Param booksprice * original book price * @ return calculate the discount price */Public double quote (double booksprice) {return this. strategy. calcprice (booksprice );}}

 

Client

Package COM. bankht. strategy;/*** @ Author: -AK47 * @ Creation Time: 10:19:48, December 26, ** @ Class description: client */public class client {public static void main (string [] ARGs) {// select and create the expected policy object memberstrategy strategy = new advancedmemberstrategy (); // create the environment Price = new price (Strategy); // calculate the price double quote = Price. quote (1, 300); system. out. println ("the final price of the book 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 in terms of implementation, and there is no dependency between them.

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.

This is also a typical scenario.CodeStandard practices in the upper-level 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.