1. Background Knowledge
Policy mode, as a software design mode, indicates that an object has a certain behavior, but in different scenarios, this behavior has different implementation algorithms. For example, everyone needs to "pay personal income tax", but "pay personal income tax in the United States" and "pay personal income tax in China" have different tax calculation methods. The policy mode encapsulates different algorithms and calls different objects to use different algorithms based on client requirements, saving a lot of code like if-else.
2. This example consists of three algorithms: algorithm 1: multiply the number by 1, algorithm 2 by 2, and algorithm 3 by 3. The client calls the second algorithm. Calculate. java-interfaces of the three algorithms
Public interface Calculate {/** algorithm interface, returns the specific algorithm */public int calnumber (int number );}
FirstCalculate. java-first algorithm, the remaining two algorithms are omitted
Public class FirstCalculate implements Calculate {@ Overridepublic int calnumber (int number) {// TODO Auto-generated method stubSystem. out. println (algorithm 1); return number ;}}
Context. java-set the algorithm Environment
Public class Context {Calculate cal;/** constructor, set the algorithm object used */public Context (Calculate cal) {this. cal = cal;}/** pass data to the corresponding algorithm */public int SetNumber (int number) {return cal. calnumber (number );}}
Client. java-entry function
public class Client {public static void main(String[] args) { Calculate cal=new SecondCalculate();Context con=new Context(cal);int result=con.SetNumber(300);System.out.println(result); } }
Result
3. Example source code
Click to download source code