Skip to content

Instantly share code, notes, and snippets.

@ajrussellaudio
Last active August 24, 2016 20:43
Show Gist options
  • Save ajrussellaudio/93b1c41eb3ed88eff5c5c99a1244effe to your computer and use it in GitHub Desktop.
Save ajrussellaudio/93b1c41eb3ed88eff5c5c99a1244effe to your computer and use it in GitHub Desktop.

#Factory Pattern

The Factory design pattern is a way of creating objects to some template, without either the instantiating function or the object classes themselves being concerned with the details of the actual creation.

##So yeah...

A Type of object superclass is defined somehow. There are examples online of this being done with abstract class inheritance and with interface composition. Since there is a chance Val Gibson may be reading this, I'll avoid using inheritance! And since there is a chance Tony is reading this, I'll use Pokemon in this example:

public interface Pokemon {
  String attack();
}

Sub-types of Pokemon, i.e. classes which implement Pokemon, can then be defined:

public class Charmander implements Pokemon {
  public String attack() {
    return "Inferno";
  }
}
public class Bulbasaur implements Pokemon {
  public String attack() {
    return "Seed Bomb";
  }
}
public class Squirtle implements Pokemon {
  public String attack() {
    return "Hydro Pump";
  }
}

Elsewhere in our code, we can create a Pokemon object using Pokemon bulbasaur = new Bulbasaur() for example. But this leads to lots of repetition. We would have to follow that with Pokemon charmander = new Charmander() and even worse, Pokemon bulbasaur2 = new Bulbasaur() and so on. This would only get worse if our new Pokemon took arguments on creation, and even worse if there were different arguments for each new Pokemon.

A better solution is to delegate the responsibility of creating Pokemon to a Pokemon Factory!

public class PokemonFactory {
  public Pokemon getPokemon(String pokedexNumber) {
    if(pokedexNumber == null){
      return null;
    }
    if(pokedexNumber == "001"){
      return new Bulbasaur();
    }
    if(pokedexNumber == "004"){
      return new Charmander();
    }
    if(pokedexNumber == "007"){
      return new Squirtle();
    }
    return null; // if pokedexNumber is anything else!
  }
}

Pokemon can then be created (chosen?) using their Pokedex entry number:

PokemonFactory pokemonFactory = new PokemonFactory();

Pokemon charmander = pokemonFactory.getPokemon("004");
charmander.attack(); // -> "Inferno"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment