java23 design patterns - Strategy Pattern

1 Structure of the strategy pattern

Strategy Mode is a package of algorithms, and algorithms use is the responsibility of segmentation algorithm itself off, delegated to different objects management. Strategy pattern usually a series of algorithms to package a series of strategies inside the class, as an abstract policy subclasses. One sentence, that is: "preparing a set of algorithms, each algorithm and encapsulated, so that they are interchangeable." Here a schematic to explain the structure of the realized pattern instance policy.

This model involves the three roles:

  ●   Environment (Context) role : to hold a reference to the Strategy.

  ●   abstract strategy (Strategy) Role : This is an abstract role, usually implemented by an interface or abstract class. This role gives specific strategies required for all class interface.

  ●   specific strategies (ConcreteStrategy) role : packaging related algorithms or behavior.

Code Example 2

Environmental class role

public class Context {
    //持有一个具体策略的对象
    private Strategy strategy;
    /**
     * 构造函数,传入一个具体策略对象
     * @param strategy    具体策略对象
     */
    public Context(Strategy strategy){
        this.strategy = strategy;
    }
    /**
     * 策略方法
     */
    public void contextInterface(){
        
        strategy.strategyInterface();
    }
    
}
复制代码

Abstract Strategy

public interface Strategy {
    /**
     * 策略方法
     */
    public void strategyInterface();
}
复制代码

Specific Strategy

public class ConcreteStrategyA implements Strategy {

    @Override
    public void strategyInterface() {
        //相关的业务
    }
}
复制代码
public class ConcreteStrategyB implements Strategy {

    @Override
    public void strategyInterface() {
        //相关的业务
    }
}
复制代码
public class ConcreteStrategyC implements Strategy {

    @Override
    public void strategyInterface() {
        //相关的业务
    }
}
复制代码

3 usage scenarios

Suppose now that the sale of all kinds of books to design a e-commerce website shopping cart system. One of the most simple case is to put all the goods unit price multiplied by the number, but the actual situation is certainly more complex than that. For example, this site may provide all the senior members of this 20% of each promotional discount; offer a 10% discount for this promotion each Intermediate Member; no discount for junior members.

  According to the description, the discount is based on the following algorithm a few:

  Algorithms one: there is no discount for junior members.

  Algorithms II: offer a 10% discount promotion for Intermediate Member.

  Algorithms III: 20% promotional discount for senior members.

  Strategies implemented using model structure is as follows:

3.1 Code

Abstract class discount

public interface MemberStrategy {
    /**
     * 计算图书的价格
     * @param booksPrice    图书的原价
     * @return    计算出打折后的价格
     */
    public double calcPrice(double booksPrice);
}
复制代码

Junior Member discount category

public class PrimaryMemberStrategy implements MemberStrategy {

    @Override
    public double calcPrice(double booksPrice) {
        
        System.out.println("对于初级会员的没有折扣");
        return booksPrice;
    }
}
复制代码

Intermediate Member discount category

public class IntermediateMemberStrategy implements MemberStrategy {

    @Override
    public double calcPrice(double booksPrice) {

        System.out.println("对于中级会员的折扣为10%");
        return booksPrice * 0.9;
    }
}
复制代码

Senior class member discount

public class AdvancedMemberStrategy implements MemberStrategy {

    @Override
    public double calcPrice(double booksPrice) {
        
        System.out.println("对于高级会员的折扣为20%");
        return booksPrice * 0.8;
    }
}
复制代码

Price class

public class Price {
    //持有一个具体的策略对象
    private MemberStrategy strategy;
    /**
     * 构造函数,传入一个具体的策略对象
     * @param strategy    具体的策略对象
     */
    public Price(MemberStrategy strategy){
        this.strategy = strategy;
    }
    
    /**
     * 计算图书的价格
     * @param booksPrice    图书的原价
     * @return    计算出打折后的价格
     */
    public double quote(double booksPrice){
        return this.strategy.calcPrice(booksPrice);
    }
}
复制代码

Client

public class Client {

    public static void main(String[] args) {
        //选择并创建需要使用的策略对象
        MemberStrategy strategy = new AdvancedMemberStrategy();
        //创建环境
        Price price = new Price(strategy);
        //计算价格
        double quote = price.quote(300);
        System.out.println("图书的最终价格为:" + quote);
    }

}
复制代码

As can be seen from the above example, the policy model encapsulation algorithm only provides new algorithms inserted into existing systems, and algorithms from the old system "retirement" method, the policy model does not decide which algorithm to use when. What algorithm to use under what circumstances is determined by the client.

4 Recognizing the Strategy pattern

The focus of the strategy pattern

  The focus of Strategy Mode is not how to implement the algorithm, but how to organize, to call these algorithms, so that the program structure is more flexible, better maintainability and scalability.

Equality of the algorithm

  Strategy mode is a great feature is the equality of each policy algorithm. For a series of specific strategies algorithms, our position is exactly the same, because this equality can be achieved interchangeable between algorithms. All algorithms policy on implementation is also independent of each other, they are not mutually dependent.

  So we can describe this series of strategy algorithms: algorithms are different strategies to achieve the same behavior.

Uniqueness when the policy runs

  During operation, the policy model in each time only one particular strategy to achieve the object, although can dynamically switch between different implementations of the policy, but only use a while.

Public behavior

  Often see is that all of the specific policy class has some public behavior. At this time, we should put these public behavior into a common strategy role-Strategy abstract class inside. Of course, this time abstract strategy role must use Java abstract class that implements the interface can not be used.

  Actually, this is a typical code standard practice focused upward hierarchy of inheritance.

5 advantages of the strategy pattern

(1) Strategy Mode provides a family of algorithms related to the management approach. Class hierarchy strategy defines a family of algorithms or behavior. Proper use inheritance can be moved to a common parent class code, the code to avoid repetition.

  (2) use the strategy pattern to avoid using multiple conditions (if-else) statements. Multiple conditional statement is not easy to maintain, take it to an algorithm which logic and arithmetic or logic or behavior which take an act of mixing together, all listed in a multiple conditional statement inside, also raw and backward than the way to use inheritance .

6 drawback of the strategy pattern

 (1) The client must know all the policy class, and the class to decide which strategy to use. This means that the client must understand the difference between these algorithms, in order to timely select the appropriate algorithm class. In other words, the policy mode is available only in the case the client knows the algorithm or behavior.

  (2) Since the mode policy for each specific strategies implemented individually packaged into classes, if many alternative strategies, then the number of objects will be very considerable.

Guess you like

Origin juejin.im/post/5ceb38016fb9a07ee565fc4b