Definition: The behavior of a class or its algorithm can be changed at runtime. In policy mode, we create an object representing various policies and a context object whose behavior changes as the policy object changes. The policy object changes the execution algorithm of the context object.
Features:
1. The algorithm can be switched freely.
2. Avoid using multiple conditions to judge.
3. Good scalability.
Applications in enterprise-level development and common frameworks: java.servlet.http.HttpServlet service method
Example: Operation behavior on two numbers.
public class Demo { public static void main(String[] args) { Strategy strategy1 = new StrategyAdd(); Strategy strategy2 = new StrategyDiv(); Context context1 = new Context(strategy1); context1.execute(10, 5); context1 = new Context(strategy2); context1.execute(10, 5); }}interface Strategy{ public void doOperation(int num1,int num2);}class StrategyAdd implements Strategy{ public void doOperation(int num1, int num2) { System.out.println("Execute addition"); System.out.println(num1+"+"+num2+"="+(num1+num2)); } }class StrategySub implements Strategy{ public void doOperation(int num1, int num2) { System.out.println("Execute subtraction"); System.out.println(num1+"-"+num2+"="+(num1-num2)); } } class StrategyMul implements Strategy{ public void doOperation(int num1, int num2) { System.out.println("Execute multiplication"); System.out.println(num1+"*"+num2+"="+(num1*num2)); } }class StrategyDiv implements Strategy{ public void doOperation(int num1, int num2) { System.out.println("Execute division"); System.out.println(num1+"/"+num2+"="+(num1/num2)); } } class Context{ private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public void execute(int num1,int num2){ strategy.doOperation(num1, num2); }}The policy model emphasizes runtime changes. Perhaps in the above code, this runtime changes are not well reflected. We can assume a practical scenario, that is, when an object parameter is passed into a method, suppose we have to choose different methods according to the different parameters, we will consider if-else to judge, while the policy model classifies these if-else, each judges a class, and then the object comes over and directly calls the policy interface method. The specific class of the object parameters belong to is judged by JVM. We do not need to understand the object parameter attribute types, etc. This not only simplifies our development work, but also has better scalability compared to if-else.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.