Java Implementation Policy mode
Steps to write the policy mode:
1. Define a public interface for the policy object;
2. Write the policy class, which implements the public interface above;
3. Save a reference to the policy object in the class that uses the policy object;
4. In the class that uses the policy object, implement the set and get methods (injections) for the policy object or use the construction method to complete the assignment
The code example implements a simple subtraction operation.
Policy interface:
Public interface Strategy {public int calculate (int a, int b);}
Policy class:
public class addstrategy implements strategy{ public int Calculate (int a, int b) { return a + b; }}public class SubstractStrategy implements Strategy{ public int calculate (int a, int b) { return a - b; }}public class multiplystrategy implements strategy{ public int Calculate (int a, int b) { return a * b; }}public class dividestrategy implements strategy{ public int calculate (int a, int b) { return a / b; }}
Classes that use the policy mode:
public class environment { private strategy strategy; public environment () {} public Environment (Strategy strategy) { this.strategy = Strategy; } public strategy getstrategy () { return strategy; } public void setstrategy (strategy strategy) { this.strategy = strategy; } public int calculate (int a, int b) { return this.strategy.calculate (a, b); } public&nBsp;int calculate (int a, int b, strategy strategy) { return strategy.calculate (a, b); }}
Specific business client:
public class client { public Static void main (String[] args) { Environment environment = new environment (New addstrategy ()); system.out.println (Environment.calculate (5, 3)); environment.setstrategy (New substractstrategy ()); system.out.println (Environment.calculate (5, 3)); system.out.println (Environment.calculate (2, 3, new multiplystrategy ())); system.out.println (Environment.calculate (6, 3, new dividestrategy ())); }}
Java record -68-java implementation policy mode