Policy mode (behavioral)

Source: Internet
Author: User

Consider the question:
A book in a bookstore is free of charge, some books are fixed at 1 yuan, some kind of book is discounted (for example, 88%) (the same category of prices). Suppose the customer buys only one kind of books, how to calculate the expense that the customer buys the book in the Design Bookstore bookstore class?

Answer:
1. You may not know how to design, after all, the above calculation rules are not the same (not a kind of book 80 percent another kind of book 90 percent as good calculation);
2. In this case, we define an interface (policy interface) that defines a method (Strategyinterface ()) as the method of calculating the amount, the implementation class object passed in to the policy interface when the bookstore class constructs the object (tell it how many books to buy when constructing the object, how much is the unit price) , the calculated amount is obtained by invoking the method of the interface.

The code for the above example is not compiled, and a generic policy pattern template is given:

Abstract policy class (used to specify policy method signatures for policy classes):

package com.shusheng.srategy;/**抽象策略类*/publicabstractclass Strategy {    //策略方法    publicabstractvoidstrategyInterface();}

Specific policy Implementation classes:

package com.shusheng.srategy;/**具体策略实现类*/publicclass ConcreteStrategy1 extends Strategy{    /**具体策略函数*/    @Override    publicvoidstrategyInterface() {        System.out.println("我是具体策略1,我将执行算法1");    }}

Specific Strategy Class 2:

package com.shusheng.srategy;/**具体策略*/publicclass ConcreteStrategy2 extends Strategy {    /**策略函数*/    @Override    publicvoidstrategyInterface() {        System.out.println("我是具体策略2,我将执行算法2");    }}

Context classes (context roles, functions: encapsulating policy patterns, avoiding the method of calling policy classes directly from outside)

 PackageCom.shusheng.srategy;/** Context Class (Context role) */ Public  class Context {     PublicStrategy strategy;//A reference to a policy object     Public Context(Strategy strategy) {//constructor to initialize the policy object when the context object is constructed         This. strategy = strategy; }/** call policy, such as this is the method of calculating the amount of bookstore * /     Public void Contextinterface(){//Exposure to external methods to avoid direct calls to the policy mode internal methods (such as Strategyinterface () is internal to the policy model)         This. Strategy.strategyinterface (); }}

Test class:

package com.shusheng.srategy;publicclass StrategyTest {    publicstaticvoidmain(String[] args) {        new Context(new ConcreteStrategy1());//初始化上下文对象时也要初始化策略类对象        context.contextInterface();//调用上下文对象的方法而不是直接调用策略对象内部的方法        new Context(new ConcreteStrategy2());//初始化上下文对象时也要初始化策略类对象        context2.contextInterface();//调用上下文对象的方法而不是直接调用策略对象内部的方法    }}

Strategy Mode Advantages:
1. The policy model provides a way to manage the associated algorithm families. (The outside world does not need to know how the internal implementation, just call the method of the context class can be)
2. Use the policy mode to avoid using multiple conditional if-else statements to implement details : Define a Policy class interface (a good policy approach), encapsulate if internal code as a method of a policy implementation class, and else internal code is encapsulated as a method of another policy implementation class. (assuming that the class containing the If-else statement is a context), the context class uses the If-else to be replaced directly with the policy method that invokes the policy interface class, and when the context is constructed, it is passed into the specific policy object. This will invoke the method of the policy class where the if-else was originally called.

Policy Mode Disadvantages:
1. As explained in the advantages of If-else, the client class must know what the specific function of the policy class is, in order to pass in the correct policy object, which means that the other person uses the interface to understand the difference between these policy algorithms, that is, the policy pattern only applies when the customer knows all the algorithms or behaviors.
2. The use of policy mode causes many policy classes, as if-(else if)-(else IF)-(else IF)-else, which produces a number of policy classes (one for each case). Of course, you can also use the enjoy meta mode to reduce the number of objects.

Application scenarios for the policy mode:
1. Multiple classes are just a slightly different scenario in the algorithm or behavior (you can extract different algorithms or behavior parts to design a policy model)
2. The algorithm needs to switch the scene freely
3. The scenario where the rule of the algorithm needs to be masked (that is, the internal implementation of the policy function is masked, the outside is just a method of calling the context)

Policy mode (behavioral)

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.