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.

  1. Strategy is like Template Method except in its granularity.
  2. State is like Strategy except in its intent.
  3. Strategy lets you change the guts of an object. Decorator lets you change the skin.
  4. State, Strategy, Bridge (and to some degree Adapter) have similar solution structures.
  5. They all share elements of the ‘handle/body’ idiom. They differ in intent - that is, they solve different problems.
  6. 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.

  • Actually the word "guts" makes me confused. Now I am little bit clear. Thanks for response. – Atish Dipongkor - MVP Jun 19 '13 at 12:04
  • +1 though when extending you have to be careful not to violate the Liskov Substitution Principle (LSP) - ie you can't go "against" the class you are extending from. – Marjan Venema Jun 19 '13 at 14:51
  • @MarjanVenema: yes, but this is not very special for the strategy pattern - LSP should be always considered when using inheritance. – Doc Brown Jun 19 '13 at 17:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.