Two Java Design Patterns: Strategy Mode

introduction

This paper describes the content of the strategy pattern. The main mode explain what strategy is and how to use the corresponding advantages and disadvantages.

  • Strategy Mode Introduction
  • The sample code
  • to sum up

First, the strategy pattern presentation

In the end what is the strategy pattern here? According to my own understanding, in short, will have the task properties of a class of unified business logic is encapsulated, the caller can according to their own business scenarios and necessary, call the business strategy.
Here Insert Picture Description
FIG understood by the policy related to the mode module includes the following three aspects:
1, the policy environment: class policy contains references;
2, Abstract Strategy: public abstract behavior policy, the policy contains all the interface method;
3, specific policy Implementation: encapsulates different strategy algorithms;

Second, the sample code

1, the policy scene

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

2, strategy interfaces

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

3, policy implementation

public class StrategyA implements Strategy {

    @Override
    public void strategyInterface() {
        //相关的业务
    }

}
public class StrategyB implements Strategy {

    @Override
    public void strategyInterface() {
        //相关的业务
    }

}

4, using strategies

public class ContextClient {
	public static void main(String[] args) {
		Strategy  StrategyA = new StrategyA();
		StrategyContext contextA = new StrategyContext(StrategyA );
		//调用策略A的执行方法
		contextA.contextInterface();
	}
}

Third, the summary

Strategy pattern usage scenarios for the algorithm to extract the package, independent of call scenarios.

Advantage of the strategy pattern:
1, when there are multiple service code determination logic, to avoid a large number of policy mode if-elsejudgment code logic to avoid confusion, Enhanced code maintainability;
2, the public part of the strategy can be highly abstract, to avoid repetition codes;

Disadvantage of the strategy pattern:
1, the caller must know all the strategy implementation class, increasing the difficulty of using the caller;
2, if it is judged more logical, then, will result in more strategy implementation class;

Published 88 original articles · won praise 49 · Views 100,000 +

Guess you like

Origin blog.csdn.net/Diamond_Tao/article/details/101904497