Work in progress... I need to get back to this.
This isn't mine, but I thought it would be handy to put here. The gist of the Factory Pattern is to reduce duplication of code and having to know a lot about the context in which part of that code is chosen at a time when that context is not necessarily known.
A factory is used when you have many, distinct implementations of the same interface (pre-Java 5, this was abstract class), while it's only at runtime that execution can decide which the caller actually needs, see DogFactory. Moreover, the caller should not need to know which implementation is in use, see FactoryPatterExample.
public interface Dog { public void speak(); }
Here are three kinds of dogs. We could add many more...
class Poodle implements Dog { public void speak() { System.out.println( "The poodle says, \"arf\"" ); } }
class Rottweiler implements Dog { public void speak() { System.out.println( "The rottweiler says (in a very deep voice), \"WOOF!\"" ); } }
class SiberianHusky implements Dog { public void speak() { System.out.println( "The husky says, \"S'up, Dude?\" "); } }
class DogFactory { public static Dog getDog( String criterion ) { if( criterion.equals( "small" ) ) return new Poodle(); else if( criterion.equals( "big" ) ) return new Rottweiler(); else if( criterion.equals( "working" ) ) return new SiberianHusky(); return null; } }
Sample use of these dogs...
What's clever here is that we can create an object of type Dog, not knowing what sort of dog it is because when we call the factory, the type (by criterion) might not be a literal (as it is here for the purposes of demonstration). However, when we use dog, variously assigned an object by the factory, it performs accurately and perfectly!
public class FactoryPatternExample { public static void main( String[] args ) { Dog dog; dog = DogFactory.getDog( "small" ); dog.speak(); dog = DogFactory.getDog( "big" ); dog.speak(); dog = DogFactory.getDog( "working" ); dog.speak(); } }
Output:
The poodle says, "arf" The rottweiler says (in a very deep voice), "WOOF!" The husky says, "S'up, Dude?"