How is strategy pattern different from the open closed principle

I have been reading the book on design patterns, thanks a lot for such a comprehensive book. However I have trouble understanding the difference between strategy pattern and open closed principle. I know one of it is a design pattern while the other is a principle, the examples are baffling me altogether. Could you please help me understand the difference between these?

@jrg.developer Can you please help with this when you get a chance? Thank you - much appreciated! :]

Great question! In case everyone isn’t familiar with the open-closed principle (OCP), let’s define it:

The open/closed principle states “Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification” - Wikipedia

That sounds complex! In simple terms, what does it mean for a class to be “open for extension, but closed for modification”?

It means you should be able to modify the behavior of a class without modifying its code.

When I first learned this, it seemed entirely contradictory– how can you modify how a class works without modifying its code? There are many ways actually!

The object-oriented programming way to do this is using inheritance: create a subclass and override any desired methods and properties. This works – you’re not modifying the code of the base class, so it satisfies OCP – but is it the best option? It may not be!

For example, if you need to override the same methods with the same behavior in multiple subclasses, you’d wind up duplicating code if you only use inheritance.

Fortunately, there’s another option: Use the strategy pattern!

The strategy pattern encapsulates concrete behavior into a “strategy” object. You can then inject the strategy – pass an instance of the strategy via init or set it as a property – wherever you need it.

Does this satisfy the OCP? It sure does! Instead of changing behavior via subclassing, you depend on protocols. Whenever you need a new behavior, you create a new strategy that implements the protocol. This can save you a lot of effort and code duplication!

Thereby, in summary:

  • The open-closed principle is a guiding principle in software development that helps you write better code.
  • The strategy pattern is one means of achieving the open-closed principle.

By the way, the OCP was made popular especially by Robert Martin’s book titled Clean Code. I highly recommend reading it, if you haven’t already!

I hope this explanation helps. Let me know if you have any other questions about this. :]

1 Like