This is the second principle of the 5 principles which are defined as an acronym S.O.L.I.D. This principle is further having an acronym called O.C.P. which is Open/Closed Principle.

The general definition of this principle is

A Class should be Open for extension but closed for modification

So to start with, we have an application where we have two types of loggers. We use a method, which takes an input and uses the type of logger required to save the data of logs. So our code would look like the following :

This code will work fine. But we have a situation, where we are required to third type of logger. Then what happens ? We have to modify this existing class and add the third type of save method, and change the existing code.

This is what is called the violation of the OCP or Open Closed principle.

So, the best way to avoid these type of situations is to use abstraction using either abstract classes or interfaces, along with the Dependency Injection. So we introduce an interface ILogger, and make our logger classes implement this interface. Then, we use the dependency injection using constructor to decide which type is to be used. So our code will become :

So now our client code will be creating an instance of the Ilogger type based on the required type and calling the LogErrors method. So our client code will be :

Does Factory method pattern violates OCP ?

We could have used the Factory method pattern to create the instance, in our example which violates OCP. But then i gave a thought on it and found that this pattern also results in violation of the OCP principle (this is what I feel as per my understanding).

To avoid such a case when we use the factory pattern, i think we could have used some kind of reflection (though not tried yet). So this was all about the concept of Open/Closed principle.

Suppose, we have 2 classes implementing an interface and a factory method returns their instance, based on the input we give to it. So when we add a third class, which implements this interface, we will need to change our existing factory method, to add code which can return the instance of the new created class. This requires us to change the existing code.This what i feel.