Behavioral Design Patterns — Strategy

The Strategy Pattern is described by the Gang of Four (GoF)as a means of encapsulating algorithms and making them interchangeable . Allowing for clients to use varying strategies interchangeably.

To understand the Strategy design pattern we must first understand the open-closed principle. The Principle says software entities should be be open for extension but closed for modification. In the Diagram below we can see the Context entity depends on a abstract entity called Strategy. Context’s behavior is closed for modification but is coupled to the Strategy abstract entity allowing for it to extend to multiple concrete strategies.

Leveraging this Structure the Strategy pattern says we can create, concrete classes of families for varying types of, algorithms that implement the Strategy interface Context is coupled to. Thus allowing for us to design single classes with multiple behaviors due to varying strategy extensions that implement the Strategy interface.

The benefit of this is rather that creating sub classes of Context that exhibit specific behaviors based on algorithms located in the class. We have a single class and provided extensions to swap strategies as needed. This allows us to have more D.R.Y.(don’t repeat yourself) code. Also, any other class can leverage the available strategies written if they use the Strategy interface.

Additionally, the strategy pattern elements the need for messy conditional statements. By not putting all your strategies in one class, but rather opening up to extension. One minus for this strategy may be overhead if the context passes unused data to the concrete strategy. It also creates a large number of objects in the application. You may want to create shareable stateless objects to lessen the impact.

Overall, the Strategy pattern lets you change an object’s core behavior. When picking your patterns you have to outline your intent first. State, Strategy, Bridge all share similar structures. What separates them is always the details which are centered around intent.