I am learning design patterns. I read this article. Point no. 3 is not clear to me. The writer said that strategy lets you change the guts of an object. But this is a violation of the open-close principle. Am I wrong? If I am wrong, then help me to understand what writer wanted to describe.
- Strategy is like Template Method except in its granularity.
- State is like Strategy except in its intent.
- Strategy lets you change the guts of an object. Decorator lets you change the skin.
- State, Strategy, Bridge (and to some degree Adapter) have similar solution structures.
- They all share elements of the ‘handle/body’ idiom. They differ in intent – that is, they solve different problems.
- Strategy has 2 different implementations, the first is similar to State. The difference is in binding times (Strategy is a bind-once pattern, whereas State is more dynamic).
Strategy objects often make good Flyweights.
Strategy lets you change the guts of an object. But it is the violation of open-close principle. Am I wrong??
No, the opposite is the case, it is a standard example for the OCP. In the shown example, you change or extend the behaviour of TransportationToAirport
(open for extensions) without modifying this class (closed for modifications). Just derive a new Strategy
object (like Train
) and use it in conjunction with your unmodified TransportationToAirport
object.
3