Is this a simple factory violation of open closing?
SimpleProductFactory needs to be changed every time you need to create a new specific product, but it adheres to the principle of single responsibility, because this is the only reason why it will ever change. Its sole purpose is to ensure that the Client does not violate the open, closed principle, so I believe that this cannot be the violation itself, since, obviously, this code is needed somewhere.
I'm not interested in changing Factory, but whether this particular example is a violation or not.
product
interface Product{ public int getPrice(); }
Milk
class Milk implements Product{ public int getPrice(){ return 5; } }
Crisps
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()); } }
java oop design-patterns solid-principles design-principles
LangLearn Korean
source share