Strategy Pattern | Set 2 (Implementation)
We have discussed a fighter example and introduced Strategy Pattern in set 1.
In this post, we apply Strategy Pattern to the Fighter Problem and discuss implementation.
The first step is to identify the behaviors that may vary across different classes in future and separate them from the rest. For our example let them be kick and jump behaviors. To separate these behaviors we will pull both methods out of Fighter class and create a new set of classes to represent each behavior.
The Fighter class will now delegate its kick and jump behavior instead of using kick and jump methods defined in the Fighter class or its subclass.
After reworking the final class diagram would be (Click on image for better view):
Comparing our design to the definition of strategy pattern encapsulated kick and jump behaviors are two families of algorithms. And these algorithms are interchangeable as evident in implementation.
Below is the Java implementation of the same.
Ken Default Punch Tornado Kick Short Jump Long Jump
Head First Design Patterns
This article is contributed by Sulabh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above