Design Mode-policy Mode
Scenario settings
Design a calculator with the following options: +,-, *, And ,-,*,/.
The main idea of the Policy mode is to encapsulate all the available algorithms and pass them in and call them through a unified container. For example:
I have an interface for computing. I insert a calculator into it, and there are calculators, reducers, and so on in the calculator. These are policies. I wrap the policies and put them into the calculator for calling, insert the calculator interface.
Therefore, the code based on this mode should be as follows:
Computing interface:
interface Operation{ public int calculate(int a, int b);}
Policy implementationStrategy
The interface keeps all policies of the same type and has a unified call method:
class AddStrategy implements Strategy{ @Override public int operate(int a, int b) { return a+b; }}class MinusStrategy implements Strategy{ @Override public int operate(int a, int b) { return a-b; }}
Calculator should be implementedOperation
Interface, used to executecalculate
:
class Calculator implements Operation{ private Strategy strategy = null; public void setStrategy(String tag){ if(tag.equals("+")){ strategy = new AddStrategy(); } if(tag.equals("-")){ strategy = new MinusStrategy(); } } @Override public int calculate(int a, int b) { return strategy.operate(a,b); }}
Finally, the following code calls the calculator:
public static void main(String[] args){ Calculator calculator = new Calculator(); calculator.setStrategy("+"); calculator.calculate(1,2); }
Rule mode is used to encapsulate algorithms. In practice, it can be used to encapsulate almost any type of rules. As long as you hear that different business rules need to be applied at different times during the analysis process, you can consider the possibility of using the Policy mode to handle such changes.
In the Basic Policy mode, the responsibility for selecting the specific implementation is borne by the client object and transmitted toCalculate
Object.
However, for policy addition and modification, you still need to modify the Calculate class. The so-called any change requires cost.