Simple Factory

Pros

  • Hides the creation logic of an object from the client
  • Refers to the created object by a common interface (ex. IMob mob instead of Zombie mob)
  • Helps avoid duplication of code when you need to create the same family of objects in multiple places

Cons

  • Violates the Open Closed principle since it has to change every time new creation requirements are needed. Since the simple factory's entire responsibility is its creation method the violation is not a huge problem. There are ways to fix the open closed violation with things like reflection if needed.

Example Explanation

SimpleMobFactory - creates and returns an object which implements the interface IMob

interface IMob{
  public int getAttack();
}

class Witch implements IMob{
  public int getAttack(){ return 5; }
}

class Zombie implements IMob{
  public int getAttack(){ return 3; }
}

class SimpleMobFactory{

  public IMob createMob(String mobName){

    if(mobName.equals("witch")){
      return new Witch();
    }
    else if(mobName.equals("zombie")){
      return new Zombie();
    }
    return null;
  }
}

class Main {
  public static void main(String[] args) {
    SimpleMobFactory mobFactory = new SimpleMobFactory();
    IMob mon = mobFactory.createMob("zombie");
    System.out.println(mon.getAttack());

  }
}

Extra Resources

Factory Design Patterns and Open-Closed Principle (OCP), the ‘O’ in SOLID

OODesign Factory

results matching ""

    No results matching ""