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());
}
}
SimpleProductFactory
class ? – PullulateSimpleProductFactory
into theClient
rather than instantiate it directly, you can subclass the factory to change its behavior without violating OCP. – Unceremonious