Java design mode-policy mode

Source: Internet
Author: User

  In the book "Java and Patterns" of Dr. Shanhong, this describes the strategy (strategy) Pattern:

  The policy mode belongs to the behavior pattern of the object. It is intended for a set of algorithms that encapsulate each algorithm in a separate class with a common interface, so that they can be replaced with each other. The policy pattern allows the algorithm to change without affecting the client.

The strategy model encapsulates a series of algorithms into a series of specific policy classes, as a subclass of an abstract policy class or an implementation class of a policy interface. To put it simply: prepare a set of algorithms and encapsulate each algorithm so that they are interchangeable.

  

  schematic sex UML diagram:

  

This pattern involves 3 characters:

Environment (context) Role: holds a reference to an strategy abstract policy class or policy interface.

Abstract policy (Strategy) role: This is an abstract role, implemented by an interface or abstract class. This role declares that all specific policy classes require an overridden method.

Specific policy (concrete strategy) role: encapsulates the associated algorithm or behavior.

Schematic example:

Environmental roles

1  Public classContext {2     // an object that holds a specific policy3     Privatestrategy strategy;4     /**5 * constructor to pass in a specific policy object6      * @paramstrategy specific policy Objects7      */8      PublicContext (Strategy strategy) {9          This. Strategy =strategy;Ten     } One     /** A * Strategy Method -      */ -      Public voidContextinterface () { the          - strategy.strategyinterface (); -     } -      +}

  Abstract policy roles

1  Public Interface Strategy {2     /** 3      * Strategy method 4      */ 5      Public void strategyinterface (); 6 }

  Specific policy roles

1  Public class Implements Strategy {23    @Override4public     void Strategyinterface () {5          Related business 6    }78 }

  

1  Public class Implements Strategy {23    @Override4public     void Strategyinterface () {5          Related business 6    }78 }

1  Public class Implements Strategy {23    @Override4public     void Strategyinterface () {5         // related Business 6     }78 }

  Using scene instances:

Suppose a website sells a variety of books, does not offer a discount to Junior members, offers a 10% discount per copy for intermediate members, and offers 20% discount for Premium members per copy of the promotion.

The discount is based on one of the following 3 algorithms:

Algorithm 1: No discounts are offered to junior members.

Algorithm 2: Offer 10% discount for intermediate members.

Algorithm 3: Offer 20% discount for Premium members.

UML diagram for this instance:

  

Discount interface

1  Public InterfaceMemberstrategy {2     /**3 * Calculate the price of a book4      * @paramthe original price of Booksprice book5      * @returncalculate the price after a discount6      */7      Public DoubleCalcPrice (Doublebooksprice);8}

  Junior Member Discount Implementation class

1  Public classPrimarymemberstrategyImplementsMemberstrategy {2 3 @Override4      Public DoubleCalcPrice (DoubleBooksprice) {5         6System.out.println ("No discount for junior members");7         returnBooksprice;8     }9 Ten}

  Intermediate Member Discount Implementation class

1  Public classIntermediatememberstrategyImplementsMemberstrategy {2 3 @Override4      Public DoubleCalcPrice (DoubleBooksprice) {5 6System.out.println ("10% Discount for mid-level members");7         returnBooksprice * 0.9;8     }9 Ten}

  Advanced Member Discount Implementation class

1  Public classAdvancedmemberstrategyImplementsMemberstrategy {2 3 @Override4      Public DoubleCalcPrice (DoubleBooksprice) {5         6System.out.println ("20% Discount for Premium members");7         returnBooksprice * 0.8;8     }9}

  Price category

1  Public classPrice {2     //hold a specific policy object3     Privatememberstrategy strategy;4     /**5 * constructor to pass in a specific policy object6      * @paramstrategy specific policy Objects7      */8      PublicPrice (Memberstrategy strategy) {9          This. Strategy =strategy;Ten     } One      A     /** - * Calculate the price of a book -      * @paramthe original price of Booksprice book the      * @returncalculate the price after a discount -      */ -      Public DoubleQuoteDoubleBooksprice) { -         return  This. Strategy.calcprice (booksprice); +     } -}

  Client

1  Public classClient {2 3      Public Static voidMain (string[] args) {4         //Select and create the policy object you want to use5Memberstrategy strategy =Newadvancedmemberstrategy ();6         //Create an environment7Price =NewPrice (strategy);8         //Calculate Price9         DoubleQuote = Price.quote (300);TenSystem.out.println ("The final price of the book is:" +quote); One     } A  -}

  The focus of the strategy pattern is not how to implement the algorithm, but how to organize, call these algorithms, so that the program structure more flexible, with better maintainability and extensibility. Policy algorithms are different implementations of the same behavior. During run time, the policy mode can only implement objects with a specific policy at each moment. Encapsulate all the common public methods of the specific policy implementation class into the abstract class, and set the code to the top of the inheritance hierarchy.

  

  

Strategy Mode Advantages:

1 The algorithm family is managed through the hierarchical structure of the policy class.

2 Avoid the multi-condition (If-else if-else) statement that will use the choice of which algorithm to mix with the implementation of the algorithm itself.

Policy Mode Disadvantages:

1 The client must know all the policy classes and decide for itself which policy class to use.

2 because the policy pattern encapsulates the specific implementation of each algorithm into a class, the objects generated for different situations become much more.

Resources

The strategy model of Java and pattern

Java design mode-policy mode

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.