Java Design Patterns Factory Method Patterns

Introduction

Factory Method Patterns define an interface for creating an object.

Factory Method Patterns let subclasses decide which class to instantiate.

Use case

  • Use factory patterns to create user interface controls.

Example

interface Animal {
   void Speak();/*from w w w  .  j a  va2  s  .  c  o  m*/
}

class Duck implements Animal {
   @Override
   public void Speak() {
      System.out.println("Duck says");
   }
}

class Tiger implements Animal {
   @Override
   public void Speak() {
      System.out.println("Tiger says");

   }
}

abstract class AnimalFactory {
   public abstract Animal GetAnimalType(String type) throws Exception;
}

class ConcreteFactory extends AnimalFactory {
   @Override
   public Animal GetAnimalType(String type) throws Exception {
      switch (type) {
      case "Duck":
         return new Duck();
      case "Tiger":
         return new Tiger();
      default:
         throw new Exception("Animal type : " + type + " cannot be instantiated");
      }
   }
}

public class Main {
   public static void main(String[] args) throws Exception {
      AnimalFactory animalFactory = new ConcreteFactory();
      Animal DuckType = animalFactory.GetAnimalType("Duck");
      DuckType.Speak();

      Animal TigerType = animalFactory.GetAnimalType("Tiger");
      TigerType.Speak();

      Animal LionType = animalFactory.GetAnimalType("Lion");
      LionType.Speak();

   }
}



PreviousNext

Related