Java design pattern-policy pattern, java design pattern --

Source: Internet
Author: User

Java design pattern-policy pattern, java design pattern --

The rule mode is the behavior mode of the object. It is intended to encapsulate an algorithm into an independent class with a common interface for mutual replacement. The policy mode allows the algorithm to change without affecting the client.

URL: http://www.cnblogs.com/wuyudong/p/5924223.html.

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 of policy mode:

1) there are multiple ways to deal with the same problem, just because the specific behavior is different,

2) When multiple operations of the same type need to be encapsulated securely

3) when the same abstract class has multiple subclasses, you must use if-else or switch-case to select the specific subclass.

Implementation of Rule Mode

For example, calculate the fare required after the specified bus or subway trip

Package com. wuyudong. strategy. normal; public class PriceCalculator {// BUS Type private static final int BUS = 1; // SUBWAY type private static final int SUBWAY = 2; public static void main (String [] args) {PriceCalculator calculator = new PriceCalculator (); System. out. println ("the fare for a 10 km bus is:" + calculator. calculatePrice (10, BUS); System. out. println ("10 km subway fare:" + calculator. calculatePrice (10, SUBWAY ));} // Calculate the public transit price private int busPrice (int km) {int extraTotal = km-10; int extraFactor = extraTotal/5; int fraction = extraTotal % 5; int price = 1 + extraFactor * 1; return fraction> 0? + Price: price;} // calculate the subway price. private int subwayPrice (int km) {if (km <= 6) {return 3 ;} else if (km> 6 & km <12) {return 4;} else if (km <22 & km> 12) {return 5 ;} else if (km <32 & km> 22) {return 6;} return 7;} // calculate the corresponding price based on the type. private int calculatePrice (int km, int type) {if (type = BUS) {return busPrice (km) ;}else {return subwayPrice (km );}}}

If you add another taxi price calculation, add the corresponding code:

Public class PriceCalculator {// BUS Type private static final int BUS = 1; // SUBWAY type private static final int SUBWAY = 2; // TAXI type private static final int TAXI = 3; public static void main (String [] args) {PriceCalculator calculator = new PriceCalculator (); System. out. println ("the fare for a 10 km bus is:" + calculator. calculatePrice (10, BUS); System. out. println ("10 km subway fare:" + calculator. calculatePrice (10, SUBWAY);} // calculate the taxi price. private int taxiprice (int km) {return km * 2 ;} // calculate the corresponding price based on the type. private int calculatePrice (int km, int type) {if (type = BUS) {return busPrice (km );} else if (type = SUBWAY) {return subwayPrice (km) ;}else {return taxiprice (km );}}}

It can be seen that the above Code is highly coupled. When a new type of transportation is added, a large amount of code needs to be constantly modified. Here we use the policy pattern reconstruction:

First, define an abstract price calculation interface:

// Calculation interface public interface CalculateStrategy {int calculatePrice (int km );}

Each travel mode defines an Independent Computing strategy class:

Bus calculation Policy

public class BusStrategy implements CalculateStrategy {    public int calculatePrice(int km) {        int extraTotal = km - 10;        int extraFactor = extraTotal / 5;        int fraction = extraTotal % 5;        int price = 1 + extraFactor * 1;        return fraction > 0 ? ++price : price;    }}

Subway computing Policy

public class SubwayStrategy implements CalculateStrategy {    public int calculatePrice(int km) {        if (km <= 6) {            return 3;        } else if (km > 6 && km < 12) {            return 4;        } else if (km < 22 && km > 12) {            return 5;        } else if (km < 32 && km > 22) {            return 6;        }        return 7;    }}

Create a role to assume the Context. The Code is as follows:

Public class TranficCalculator {CalculateStrategy mStrategy; public static void main (String [] args) {TranficCalculator calculator = new TranficCalculator (); // sets the calculation policy calculator. setStrategy (new BusStrategy (); // calculates the price of System. out. println ("price of 10 km by bus:" + calculator. calculatePrice (10);} public void setStrategy (CalculateStrategy mStrategy) {this. mStrategy = mStrategy;} public int calculatePrice (int km) {return mStrategy. calculatePrice (km );}}

In this way, even if you need to add a taxi price calculation, you only need to create a new class to inherit from the CalculateStrategy interface and implement the method.

Advantages

1) clear structure, simple and intuitive use

2) relatively low coupling and convenient scalability

3) operation encapsulation is more location-based and data-based.

Disadvantages

Subclass increase

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.