Factory | Abstract Factory |
Singleton | Builder |
Prototype | Adapter |
Bridge | Composite |
Decorator | Facade |
Flyweight | Proxy |
Chain of Responsibility | Command |
Interpreter | Iterator |
Mediator | Memento |
Observer | State |
Strategy | Template |
Visitor |
public abstract class Dog { public abstract void speak (); } public class Poodle extends Dog { public void speak() { System.out.println("The poodle says \"arf\""); } } public class SiberianHusky extends Dog { public void speak() { System.out.println("The husky says \"Whazzup?!!\""); } } public class Rottweiler extends Dog { public void speak() { System.out.println("The Rottweiler says (in a very deep voice) \"WOOF!\""); } }
public class Main { public Main() { // create a small dog Dog dog = DogFactory.getDog("small"); dog.speak(); // create a big dog dog = DogFactory.getDog("big"); dog.speak(); // create a working dog dog = DogFactory.getDog("working"); dog.speak(); } public static void main(String[] args) { new Main(); } }
public class DogFactory { public static Dog getDog(String criteria) { if ( criteria.equals("small") ) return new Poodle(); else if ( criteria.equals("big") ) return new Rottweiler(); else if ( criteria.equals("working") ) return new SiberianHusky(); return null; } }