1. 程式人生 > >Coding Dynamic Behavior with the Strategy Pattern

Coding Dynamic Behavior with the Strategy Pattern

Polymorphism through Strategies

The strategy pattern, also known as the policy pattern, is a behavioral design pattern that lets an object execute some algorithm (strategy) based on external context provided at runtime. This pattern is particularly useful when you have an object that needs to be able to execute a single behavior in different ways at different times. By using the strategy pattern, you can define a set of algorithms that can be dynamically provided to a particular object if/when they are needed. This pattern has a number of benefits, including: encapsulation of particular algorithms in their own classes; isolation of knowledge about how algorithms are implemented; and, code that is more flexible, mobile, and maintainable. To the last point, you may note that these are the same attributes that result from code that follows the

Open/Closed Principle (OCP) and indeed, the strategy pattern is an excellent way to write OCP-adherent code.

When implementing the strategy pattern, you need three main elements:

  1. A client, which is aware of the existence of some abstract strategy but may not know what that strategy does or how it does it.
  2. A set of strategies that the client can use if/when provided with one of them. These may come in the form of first-class functions, objects, classes, or some other data structure.
  3. Optional context that the client can provide to its current strategy to use in execution.

The classic way to implement strategies is with interfaces. In this case, a client has an internal pointer to some abstract strategy interface, which is then pointed to a concrete strategy implementation via dependency injection (that is, during construction or with a setter at runtime). Thereafter, the client may use the provided strategy to carry out some work, all without knowing (or caring) what the strategy actually does.

Although interfaces are the classic way to implement the strategy pattern, a similar effect may be achieved in languages that do not have interfaces. What is important is that the client is aware of some abstract strategy and is able to execute that strategy without knowledge of its inner workings.