~ The same as Template Method, but implement by Delegation instead of Inheritance
The Strategy pattern is a behavioral design pattern that allows you to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. This pattern lets the algorithm vary independently from the clients that use it.
In Ruby on Rails, the Strategy pattern can be used to encapsulate different algorithms that can be used to perform a specific task, depending on the context or requirements of the application. Here are a few examples of how the Strategy pattern can be implemented in Ruby on Rails:
The Template Method
pattern has some drawbacks, most of which stem from
the fact that this pattern is built around inheritance. On top of this, inheritance-based techniques such as the Template Method pattern limit our runtime flexibility.
The alternative of using inheritance is to follow that bit of GoF advice: Prefer delegation
.
Template Method
Strategy
The strategies
, which all do the same thing—in our example, format the report. Not only does each strategy object perform the same job
, but all of the objects support
exactly the same interface.
The Strategy
pattern does have one thing in common with the Template Method
pattern: Both patterns allow us to concentrate the decision
about which variation
we are using
in one or a few places. With the Template Method pattern, we make our decision when we pick our concrete subclass. In the Strategy pattern, we make our decision by selecting a strategy class at runtime.
Context: Report
Strategy: PlainTextFormatter
, HTMLFormatter
A real advantage of the Strategy pattern is that because the context and the strategy code are in different classes, a nice wall of data separation divides the two. We have essentially two choices:
everything
that the strategy needs as arguments