Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Always use the Strategy design pattern for operations like this below.</p> <p>//StrategyExample test application</p> <p>public class StrategyExample { public static void main(String[] args) { Context context; // Three contexts following different strategies context = new Context(new ConcreteStrategyAdd()); int resultA = context.executeStrategy(3, 4); context = new Context(new ConcreteStrategySubtract()); int resultB = context.executeStrategy(3, 4); context = new Context(new ConcreteStrategyMultiply()); int resultC = context.executeStrategy(3, 4); } }</p> <p>//The classes that implement a concrete strategy should implement this // The context class uses this to call the concrete strategy public interface Strategy { int execute(int a, int b); }</p> <p>//Implements the algorithm using the strategy interface public class ConcreteStrategyAdd implements Strategy { public int execute(int a, int b) { System.out.println("Called ConcreteStrategyA's execute"); return a + b; // Do an addition with a and b } }</p> <p>public class ConcreteStrategySubtract implements Strategy { public int execute(int a, int b) { System.out.println("Called ConcreteStrategyB's execute()"); return a - b; // Do a subtraction with a and b } }</p> <p>public class ConcreteStrategyMultiply implements Strategy { public int execute(int a, int b) { System.out.println("Called ConcreteStrategyC's execute()"); return a * b; // Do a multiplication with a and b } }</p> <p>//Configured with a ConcreteStrategy object and maintains a reference to a Strategy object public class Context { private Strategy strategy;</p> <pre><code>// Constructor public Context(Strategy strategy) { this.strategy = strategy; } public int executeStrategy(int a, int b) { return strategy.execute(a, b); } </code></pre> <p>}</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload