definition: The behavior of a class or its algorithm can be changed at run time. In the policy model, we create the objects that represent the various policies and a context object that behaves as the policy object changes. The policy object changes the execution algorithm of the context object.
Characteristics:
1, the algorithm can be freely switched.
2, avoid the use of multiple conditions to judge.
3, the expansion of good.
Enterprise-class development and applications in common frameworks: Java.servlet.http.HttpServlet Service method
Example: an action behavior of two digits.
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 ("perform addition");
System.out.println (num1+ "+" +num2+ "=" + (num1+num2));
Class Strategysub implements strategy{public void dooperation (int num1, int num2) {System.out.println ("perform subtraction");
System.out.println (num1+ "-" +num2+ "=" + (num1-num2));
Class Strategymul implements strategy{public void dooperation (int num1, int num2) {System.out.println ("perform multiplication");
SYSTEM.OUT.PRINTLN (num1+ "*" +num2+ "=" + (num1*num2));
Class Strategydiv implements strategy{public void dooperation (int num1, int num2) { SYSTEM.OUT.PRINTLN ("perform 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 pattern emphasizes the run-time changes, which may be in the code above, and this run-time change is not well represented, and we can assume that a real scenario is when an object parameter is passed to a method, assuming we have to choose different methods depending on the parameters. We will consider the if-else to judge, and the strategy pattern is to classify these if-else, each judge a class, then the object come over, call the policy interface method directly, and the object parameter belongs to which specific class is the JVM to judge, We don't have to understand the object parameter attribute type, which simplifies our development work and is more scalable than if-else.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.