Is this Simple Factory violating the Open Closed Principle?
The SimpleProductFactory needs to change every time a new concrete product needs to be created but it adheres to the single responsibility principle because that is the only reason it will ever change. Its sole purpose is so that the Client does not violate the open closed principle so I imagine it can't be a violation itself since obviously this code is needed somewhere.
I am not interested in changing the factory but whether this specific example is a violation or not.
Product
interface Product{
public int getPrice();
}
Milk
class Milk implements Product{
public int getPrice(){ return 5; }
}
Chips
class Chips implements Product{
public int getPrice(){ return 3; }
}
SimpleProductFactory
class SimpleProductFactory{
public Product createProduct(String productName){
if(productName.equals("milk")){
return new Milk();
}
else if(productName.equals("chips")){
return new Chips();
}
return null;
}
}
Client
class Client{
public static void main(String[] args) {
SimpleProductFactory productFactory = new SimpleProductFactory();
Product prod = productFactory.createProduct("milk");
System.out.println(prod.getPrice());
}
}
Example code is not production quality code, any you shouldn't expect it to be. The pattern itself doesn't violate the Open/Closed Principle (OCP). However, we violate the OCP when we use the pattern incorrectly. Create your base functionality using Factory Method Pattern. EXTEND your functionality by using the Abstract Factory Pattern
The Open/Closed Principle states that software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. What it means, in essence, is that when we need to introduce a change, we shouldn’t dig deep into the system and change its behavior by changing dozens of classes.
The open-closed principle, as the Liskov substitution principle, applies to class trees, to inheritance hierarchies. In your example, the factory class is not in the family tree of the classes it instantiates so it cannot violate these rules.
Therefore, there is no way that writing a factory class can forego the if statements. It would shift the burden of choosing a specific class to the caller, which is exactly what the pattern is supposed to avoid.
Is this Simple Factory violating the Open Closed Principle?
To answer your questions. "Yes, Simple Factory violates the Open Closed Principle for a reason."
The Simple Factory pattern supposed to be modified in order to help us choosing specific class to the caller. If we make this class conforming to open closed principle then we have to shift burden to some other class and this class will not serve the purpose of factory anymore. Not all principles are absolute. We need to weigh the benefits when using or when not using.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With