The intent of Strategy pattern is to define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets a class behavior or its algorithm can be changed at run time. It captures the abstraction in an interface, and provides implementation details in derived classes.
Here is one example to demonstrate Decorator pattern implementation and usage.
Strategy class
1 2 3 4 5 6 7 |
package net.tecbar.designpattern.strategy; public interface Strategy { void doOpeation(); } |
Concrete strategy classes
1 2 3 4 5 6 7 8 9 10 11 |
package net.tecbar.designpattern.strategy; public class StrategyA implements Strategy { @Override public void doOpeation() { System.out.println("execute algorithm in StrategyA"); } } |
1 2 3 4 5 6 7 8 9 10 11 |
package net.tecbar.designpattern.strategy; public class StrategyB implements Strategy { @Override public void doOpeation() { System.out.println("execute algorithm in StrategyB"); } } |
Context class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package net.tecbar.designpattern.strategy; public class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public void myMethod() { strategy.doOpeation(); } } |
Client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package net.tecbar.designpattern.strategy; public class StrategyDemo { public static void main(String[] args) { Context ctx = new Context(new StrategyA()); ctx.myMethod(); Context ctx2 = new Context(new StrategyB()); ctx2.myMethod(); } } |
Output
execute algorithm in StrategyA
execute algorithm in StrategyB
Pingback: Software Design Patterns