The Strategy

Intent: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it (Gamma et al., 1994).

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 depends 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 General Services Administration (GSA).

images

Figure 18: Strategy example diagram.

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 (see p. 38) of the strategy interface.

Questions and Concerns: Strategy adds a virtual method call to the system, which can impede performance. It removes all intimacy between the algorithm and the state which it operates on; the state must be passed in/back.

Strategy requires all versions of the algorithm to have the same interface and to be castable to the same base type. If this is not true, an adapter (see p. 18) can be used to resolve this.

Strategy allows all versions of an algorithm to be used interchangeably. If there are business rules about which version should be used and under what circumstances, another pattern must be used to enforce them: typically, one of the creational patterns, depending on the domain.

For more information: https://tinyurl.com/y2q5gdep

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.88.62