The Strategy Design Pattern in Java(II)
14 March 2008Please read the first part of this post.
Though it looks like that Strategy design pattern and Bidge Design patterns are same, they are different. While Strategy design pattern is behavioral design pattern the Bidge Design pattern is structural design pattern. In the Strategy design pattern coupling between the context and the strategies is tighter where as in the bridge design pattern the coupling between the abstraction and the implementation is not as tight.
As per the Strategy pattern the behavior of a class should be encapsulated using interfaces instead of inheriting it.
How to implement the Strategy pattern
1. Create the strategy interface.
2. Implement the algorithm using the strategy interface
3. Configure the Context class and maintain a reference to a Strategy object
4. In the Context class, implement public get and set methods for the Strategy object
Example: StrategyPatternDemo.java
class StrategyPatternDemo { public static void main(String[] args) { Context context; context = new Context(new Strategy1()); context.execute(); context = new Context(new Strategy2()); context.execute(); context = new Context(new Strategy3()); context.execute(); } } interface MyStrategyInterface { void execute(); } class Strategy1 implements MyStrategyInterface { public void execute() { System.out.println( "Called Strategy1.execute()" ); } } class Strategy2 implements MyStrategyInterface { public void execute() { System.out.println( "Called Strategy2.execute()" ); } } class Strategy3 implements MyStrategyInterface { public void execute() { System.out.println( "Called Strategy3.execute()" ); } } class Context { MyStrategyInterface strategy; public Context(MyStrategyInterface strategy) { this.strategy = strategy; } public void execute() { strategy.execute(); } }
Related Posts:
- The Strategy Design Pattern in Java(I)
- Singleton - Creational Design Pattern (I)
- The Observer Design Pattern(I)
- Adapter design pattern
- The Facade Design Pattern (I)
- Design Patterns - Basics (I)
- The Facade Design Pattern (II)
- Adapter design pattern (II)
- Singleton - Creational Design Pattern (II)
- Behavioral Pattern - Iterator Pattern (Example) - 1
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: The Strategy Design Pattern in Java(II)