The Strategy

Listen to this post
Subscribe

Intent

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. (GoF)

Example

Businesses purchase various equipment, properties, vehicles and so forth as required to operate. The cost of these “assets” can be deducted from the profits of the business, reducing their tax liability.

However, it is not permissible to “write off” the entire value of an asset immediately, it must be done gradually over time using an algorithm for what is termed “fixed asset amortization”. There are various algorithms for doing this, the right one depending on a number of factors: type of asset, which governmental entity is being reported to, where it was purchased, etc.

Amortization is often “capped” at a maximum and is dependent on a “business domain” code from the GSA.

Diagram

Strategy Pattern

Qualities and principles

Each Strategy object is responsible for one version of the algorithm and is thus cohesive. Any potentially redundant elements can be pulled up into the base class. Clients couple only to the Strategy interface; all specific algorithm implementations are encapsulated and open-closed. Strategy objects are substitutable for one another. The interface of the Strategy is derived from client need, not from any particular implementation. Strategy separates the concern of the algorithm from all other concerns.

Testing

Each Strategy implementation can be tested on its own. The Context object (Asset, in the example) can be tested using a Mock of the Strategy interface.

Questions and concerns

Strategy adds a virtual method call to the system, which can impede performance. Strategy requires all versions of the algorithm to have the same interface and to be cast-able to the same base type. If this is not true, an Adapter can be used to solve this problem.

Strategy allows all versions of an algorithm to be used interchangeably. If there are business rules about which version should be used and when, another pattern must be used to enforce them, depending on the domain.

More information

Visit the Net Objectives Pattern Repository: Strategy Pattern

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.