Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open closed principle vs Strategy pattern

I have read both strategy pattern and open closed principle both look same to me.If they are same why we have different name pattern \principle for them.

Please share your thoughts on this one.

like image 203
Varun Avatar asked Oct 25 '12 10:10

Varun


People also ask

Which design pattern uses Open Closed Principle?

In a nutshell, the developer must need to change only a specific part of the code (a class or a function) every time a requirement changes. Using a statically typed language like Java, C#, etc. the open/closed principle is generally achieved by using inheritance and polymorphism.

When should you use Strategy pattern?

Use the Strategy pattern when you want to use different variants of an algorithm within an object and be able to switch from one algorithm to another during runtime. Use the Strategy when you have a lot of similar classes that only differ in the way they execute some behavior.

What is meant by the Open Closed Principle?

In object-oriented programming, the open–closed principle states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"; that is, such an entity can allow its behaviour to be extended without modifying its source code.

What is the difference between strategy and bridge pattern?

Strategy Pattern is used for Behavioural decisions, while Bridge Pattern is used for Structural decisions. Brigde Pattern separats the abstract elements from the implementation details, while Strategy Pattern is concerned making algorithms more interchangeable.


1 Answers

OCP comes at a much more general level than Strategy - that's why it is a principle rather than a pattern. OCP doesn't state that there should be a class X that does Y and Z and collaborates in W way with another class. It only states that classes should be closed to modification but open for extension.

You can achieve OCP in a class by externalizing some of its responsibilities to a Strategy and writing new Strategies instead of modifying the class itself, but it is not the only way of respecting OCP. There are other patterns that help achieve OCP, like Abstract Factory.

like image 190
guillaume31 Avatar answered Sep 20 '22 18:09

guillaume31