Java Design Pattern--policy mode

Source: Internet
Author: User

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.

This article address: http://www.cnblogs.com/wuyudong/p/5924223.html, reprint please indicate source Address.

Structure of the policy pattern

The strategy pattern is the wrapper over the algorithm, which separates the responsibility of the algorithm and the algorithm itself, delegating to different object Management. The strategy pattern typically wraps a series of algorithms into a set of policy classes as subclasses of an abstract policy class. In a word, it is: "prepare a set of algorithms and encapsulate each algorithm so that they can be interchanged." The following is a schematic implementation of the structure of the policy pattern instance.

This pattern involves three characters:

Environment (context) Role: holds a reference to a strategy.

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

specific policy (concretestrategy) role: wraps the associated algorithm or Behavior.

Usage Scenarios for policy mode:

1) to deal with the same problem in a variety of ways, just because the specific behavior is different,

2) requires safe encapsulation of multiple operations of the same type

3) when there are multiple subclasses of the same abstract class, and you need to use If-else or switch-case to select a specific subclass.

Implementation of the policy pattern

For example, calculate the fares required for buses and subways to run after a specified distance

 packagecom.wuyudong.strategy.normal; public classPricecalculator {//Bus Type    Private Static Final intBUS = 1; //Subway type    Private Static Final intSUBWAY = 2;  public Static voidmain (string[] Args) {pricecalculator calculator=NewPricecalculator (); System.out.println ("the fare for the 10-kilometer bus is:" + calculator.calculateprice (10, BUS)); System.out.println ("the fare for the 10-kilometer subway is:" + calculator.calculateprice (10, SUBWAY)); }        //Calculate bus Prices    Private intBusprice (intKm) {        intExtratotal = km-10; intExtrafactor = EXTRATOTAL/5; intfraction = extratotal% 5; intPrice = 1 + extrafactor * 1; returnFraction > 0? ++price:price; }    //Calculate Metro Prices    Private intSubwayprice (intKm) {        if(KM <= 6) {            return3; } Else if(km > 6 && miles < 12) {            return4; } Else if(km < i && km > 12) {            return5; } Else if(km < + && km > 22) {            return6; }        return7; }    //calculates the corresponding price according to the type    Private intCalculateprice (intkm,intType) {        if(type = =BUS) {            returnBusprice (km); } Else {            returnSubwayprice (km); }    }}

If you add another Taxi's price calculation, add the corresponding code:

 public classPricecalculator {//Bus Type    Private Static Final intBUS = 1; //Subway type    Private Static Final intSUBWAY = 2; //Taxi type    Private Static Final intTAXI = 3;  public Static voidmain (string[] Args) {pricecalculator calculator=NewPricecalculator (); System.out.println ("the fare for the 10-kilometer bus is:" + calculator.calculateprice (10, BUS)); System.out.println ("the fare for the 10-kilometer subway is:" + calculator.calculateprice (10, SUBWAY)); }    //Calculate Taxi prices    Private intTaxiprice (intKm) {        returnKM * 2; }    //calculates the corresponding price according to the type    Private intCalculateprice (intkm,intType) {        if(type = =BUS) {            returnBusprice (km); } Else if(type = =SUBWAY) {            returnSubwayprice (km); } Else {            returnTaxiprice (km); }    }}

It can be seen that the above code is more coupled, and whenever a new type of vehicle is added, a lot of code needs to be constantly modified, which is reconstructed using the policy mode:

First define an abstract price-computing interface:

// Compute Interface  public Interface calculatestrategy {    int calculateprice (int  km);}

Each method of travel defines a separate calculation strategy class:

Bus calculation strategy

 public  class  busstrategy implements   calculatestrategy { public< /span> int  calculateprice (int   int  extratotal = Km-10;         int  extrafactor = Extratotal/5;         int  fraction = extratotal% 5;         int  price = 1 + extrafactor * 1;  return  fraction > 0?    ++price:price; }}

Subway calculation strategy

 public classSubwaystrategyImplementsCalculatestrategy { public intCalculateprice (intKm) {        if(KM <= 6) {            return3; } Else if(km > 6 && miles < 12) {            return4; } Else if(km < i && km > 12) {            return5; } Else if(km < + && km > 22) {            return6; }        return7; }}

Then create a role that plays the context, with the following code:

 public classTranficcalculator {calculatestrategy mstrategy;  public Static voidmain (string[] Args) {tranficcalculator calculator=NewTranficcalculator (); //set up a calculation policyCalculator.setstrategy (NewBusstrategy ()); //Calculate PriceSystem.out.println ("bus by 10 km price:" + calculator.calculateprice (10)); }         public voidsetstrategy (calculatestrategy Mstrategy) { this. Mstrategy =mstrategy; }     public intCalculateprice (intKm) {        returnMstrategy.calculateprice (km); }}

This way, even if you need to add a Taxi's price calculation, simply create a new class to inherit from the Calculatestrategy interface and implement one of the methods

Advantages

1) clear structure, Simple and intuitive to use

2) The coupling degree is relatively low, the expansion is convenient

3) operation package Because more ground, data more secure

Disadvantages

Increase in sub-categories

Java Design Pattern--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.