Design Pattern 18-strategy pattern (behavior pattern)

Source: Internet
Author: User
1. Scenario Simulation

Simple quotation management system:
Full price for common and new users
5% discount for old customers
10% discount for major customers
2. No mode solution

Package demo16.strategy. example2;/*** price management, mainly used to calculate the price quoted to the customer */public class price {/***. For different types, calculate different prices * @ Param goodsprice original sales price * @ Param customertype customer type * @ return calculated, the price should be quoted to the customer */Public double quote (double goodsprice, string customertype) {If ("regular customer ". equals (customertype) {return this. calcpricefornormal (goodsprice);} else if ("old customer ". equals (customertype) {return this. calcpriceforold (goodsprice);} else if ("major account ". equals (customertype) {return this. calcpriceforlarge (goodsprice);} // the rest of the staff report the original price return goodsprice ;} /*** calculate the quoted price for a new or common customer * @ Param goodsprice original price * @ return calculated, price to be quoted */private double calcpricefornormal (double goodsprice) {system. out. println ("No discounts for new or common customers"); Return goodsprice ;} /*** calculate the quoted price for the old customer * @ Param goodsprice original sales price * @ return calculated, should be quoted to the customer */private double calcpriceforold (double goodsprice) {system. out. println ("5% discount for old customers"); Return goodsprice * (1-0.05 );} /*** calculate the quoted price for major customers * @ Param goodsprice original sales price * @ return calculated, the price should be quoted to the customer */private double calcpriceforlarge (double goodsprice) {system. out. println ("10% discount for major accounts"); Return goodsprice * (1-0.1 );}}
3. What's the problem?

This is often the case. During the company's anniversary, all customers will receive an additional 3% discount. During the quarter-over period, regular users will receive an additional 3% discount, and after the promotion time, the price will rise again, so this price category will be very huge, and there are many methods.
Seeing this, my friends soon thought: how can we make the algorithm for calculating the quotation in the price class easily implement maintenance, scalability, and dynamic switching and change?
4. Use the policy mode to Solve the Problem 4.1 define the policy Mode

Define a series of algorithms, encapsulate them one by one, and replace them with each other. This mode allows algorithms to change independently of customers who use them.
4.2 structure of policy Mode

 
4.3 Sample Code of policy Mode

Package demo16.strategy. example3;/*** policy, which defines the algorithm interface */public interface Strategy {/*** an algorithm interface, which can contain input parameters, you can also return the value */Public void algorithminterface ();} **************************************** * **************************** package demo16.strategy. example3;/*** implement the specific algorithm */public class concretestrategya implements Strategy {public void algorithminterface () {// specific Algorithm Implementation }}******************************* * *********************************** package demo16.strategy. example3;/*** implement the specific algorithm */public class concretestrategyb implements Strategy {public void algorithminterface () {// specific Algorithm Implementation} package demo16.strategy. example3;/*** implement the specific algorithm */public class concretestrategyc implements Strategy {public void algorithminterface () {// specific Algorithm Implementation }}******************************* * *********************************** package demo16.strategy. example3;/*** context object, usually holding a specific policy object */public class context {/*** holding a specific policy object */private strategy Strategy; /*** constructor to input a specific policy object * @ Param astrategy specific policy object */public context (Strategy astrategy) {This. strategy = astrategy;}/*** the operation interface provided by the context to the client, which can have parameters and return values */Public void contextinterface () {// It usually calls a specific policy object for algorithm calculation strategy. algorithminterface ();}}
5. Rewrite the instance in policy Mode
Package demo16.strategy. example4;/*** policy, define the quote algorithm calculation interface */public interface Strategy {/*** calculate the quoted price * @ Param goodsprice product sales price * @ return calculated, price to be quoted */Public double calcprice (double goodsprice );} **************************************** * ******************************* package demo16.strategy. example4;/*** specific Algorithm Implementation: Calculate the expected price for new or common customers */public class normalcustomerstrategy implements Strategy {public double calcprice (double goodsprice) {system. out. println ("No discounts for new or common customers"); Return goodsprice ;}} **************************************** * ***************************** package demo16.strategy. example4;/*** specific Algorithm Implementation: Calculate the quoted price for old customers */public class oldcustomerstrategy implements Strategy {public double calcprice (double goodsprice) {system. out. println ("5% discount for old customers"); Return goodsprice * (1-0.05 );}} **************************************** * ***************************** package demo16.strategy. example4;/*** specific Algorithm Implementation: Calculate the expected price for major customers */public class largecustomerstrategy implements Strategy {public double calcprice (double goodsprice) {system. out. println ("10% discount for major accounts"); Return goodsprice * (1-0.1 );}} **************************************** * ***************************** package demo16.strategy. example4;/*** price management, mainly completes the calculation function */public class price {/*** holding a specific policy object */private strategy Strategy = NULL;/*** constructor, input a specific policy object * @ Param astrategy specific policy object */Public price (Strategy astrategy) {This. strategy = astrategy;}/*** quotation, calculated for the customer's quote * @ Param goodsprice product sales price * @ return calculated, price to be quoted */Public double quote (double goodsprice) {return this. strategy. calcprice (goodsprice );}} **************************************** * ***************************** package demo16.strategy. example4; public class client {public static void main (string [] ARGs) {// 1: select and create the required policy object strategy Strategy = new largecustomerstrategy (); // 2: Create the context price CTX = new price (Strategy); // 3: Calculate the quote double quote = CTX. quote (1, 1000); system. out. println ("quoted to the customer:" + quote );}}
6. Mode explanation 6.1 Key Points

Function:Separate specific algorithms from specific business processing, and implement them into separate algorithm classes to form a series of algorithms that can be replaced with each other.
Policy algorithms are different implementations of the same behavior
When to choose
: Multiple if-else statements can be selected.
6.2 call sequence of policy Mode

First, the client selects and creates a specific policy object.
Create a context
Finally, the context method is called to execute the function.
 
6.3 when a new policy is added

The following code is easy and convenient?
// 1: select and create the policy object to be used
Strategy Strategy = new largecustomerstrategy ();
6.4 call another policy Mode

 
6.5 advantages and disadvantages

Advantage: defines a series of algorithms to avoid using multiple conditional statements for better scalability
Disadvantage: the client must understand the differences between each policy and increase the number of objects. It is only applicable to flat algorithm structures (Equal Status algorithms)
6.6 nature of design patterns

Separation algorithm, select implementation

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.