Skip to content
APPCITORThe Tech Blog
Esc

Behavioral – Strategy Design Pattern

August 18, 2020 1 min read

Behavioral – Strategy Design Pattern

Strategy pattern is also known as Policy Pattern. We define multiple algorithms and let client application pass the algorithm to be used as a parameter. Strategy pattern is a Behavioral design pattern that defines a family of algorithms, encapsulates each algorithm, and makes the algorithms interchangeable within that family.

Let’s see how to implement the strategy pattern using an example.

This example is on the behaviors of a boxer who are using some strategies.

Here it is created the “Boxer” abstract class as boxer is the specific class to the program. You can see two behaviors inside the class. Let’s see how to implement those classes from the next step. Also there are two methods called “kick()” and “strike()” delegate to those behaviors. And “punch()” method is common.

“KickBehavior” interface is one of the behavior and “frontKick” and “sidekick” are the strategies use by the boxers under the kick behavior. Because of that those classes are implemented by the interface.

Here also same as the kick behavior. “StrikeBehavior” is the interface and its strategies “FaceStrike” and “LegStrike” are implemented by that interface.

“William” and “David” are the two boxers or the characters used for the program. Because of that those classes are extended by the abstract class “Boxer”.

Let’s see the main method or the driver class.

Here first I made some behaviors. Then I made a boxer with desired behaviors. Next I called the methods to test the behaviors. At last I changed the behavior dynamically.

Output:

You can visit the below given articles to learn about creational design patterns and Structural Design Patterns.

Thank you.

Creational Design Patterns

Singleton Design Pattern

Factory Design Pattern

Abstract Factory Design Pattern

Prototype Design Pattern

Builder Design Pattern

Structural Design Patterns

Facade Design Pattern

Decorator Design Pattern

Adapter Design Pattern

Bridge Design Pattern

Composite Design Pattern

Proxy Design Pattern

Flyweight Design Pattern

Share this article

Keep reading