dimanche 31 décembre 2017

Is this Simple Factory violating the Open Closed Principle?

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());

  }
}

Aucun commentaire:

Enregistrer un commentaire