Saturday, December 10, 2016

OCP - Open Closed Principle - Example

Example of OCP - A fruit selling application which has SalesManager class as below:

The problem with the above SalesManager code is that, whenever a new fruit is being introduced, the method SellFruits() needs to be modified which breaks OCP. So now, how do we resolve this issue? We can do something like below code:


Now, if a new fruit is being introduced, we don't need to modify method SellFruits() of SalesManager class, we just have to create a new class and make that class implement IFruit interface.

The fruit checking logic need to be moved to some place, in this case it is being moved to the class who is making use of the class SalesManager. So whenever a new fruit is being introduced only this par of the code need to be modified.

Well, the above code can be fixed using reflection, if the Assembly name is known and the fruit name resembles the fruit class created. Even if there is a new fruit introduced, there is no change required in the code if the code is written as below using reflection. 



Basically while using the above code we will be having classes like below, and based on the fruitName variable value, the instance of that class will be created during run-time.
  • For apple - OCP.Apple.
  • For orange OCP.Orange
  • For pineapple - OCP.Pineapple
  • For banana - OCP.Banana

No comments:

Post a Comment