Thursday, October 30, 2014

Factory Pattern


package com.exmpl.factoryPattern;

public interface Animal {
       void getVoice();
}
package com.exmpl.factoryPattern;

public class Dog implements Animal {

       @Override
       public void getVoice() {
              System.out.println("Dog voice --- Bark Bark Bark Bark Bark");
       }
}
package com.exmpl.factoryPattern;

public class Cat implements Animal {

       @Override
       public void getVoice() {
              System.out.println("Cat voice --- Meow Meow Meow Meow Meow");
       }
}
package com.exmpl.factoryPattern;

public class Tiger implements Animal {

       @Override
       public void getVoice() {
              System.out.println("Tiger voice --- Growl Growl Growl Growl Growl");
       }
}
package com.exmpl.factoryPattern;

/*This is the factory class, which create specific animal based on animal type supplied.*/
public class AnimalFactory {
       final static String TIGER = "tiger";
       final static String DOG = "dog";
       final static String CAT = "cat";

       public Animal getAnimal(String animalType) {
              Animal returnAnimal = null;
              if (animalType != null) {
                     if (animalType.equalsIgnoreCase(TIGER)) {
                           returnAnimal = new Tiger();
                     } else if (animalType.equalsIgnoreCase(DOG)) {
                           returnAnimal = new Dog();
                     } else if (animalType.equalsIgnoreCase(CAT)) {
                           returnAnimal = new Cat();
                     }
              }
              return returnAnimal;
       }
}
package com.exmpl.factoryPattern;

public class ClientClass {

       public static void main(String[] args) {
              AnimalFactory animalFactory = new AnimalFactory();

              // Get tiger object from AnimalFactory and check it's voice.
              Animal animal1 = animalFactory.getAnimal("tiger");
              animal1.getVoice();

              // Get dog object from AnimalFactory and check it's voice.
              Animal animal2 = animalFactory.getAnimal("dog");
              animal2.getVoice();

              // Get cat object from AnimalFactory and check it's voice.
              Animal animal3 = animalFactory.getAnimal("cat");
              animal3.getVoice();
       }
}
Output รจ
Tiger voice --- Growl Growl Growl Growl Growl
Dog voice --- Bark Bark Bark Bark Bark

Cat voice --- Meow Meow Meow Meow Meow

No comments:

Post a Comment