Thursday, 28 April 2016

Factory design pattern

Factory design pattern

Factories are used to return a certain type of objects based on the arguments provided to it.
It makes sense of using a singleton design pattern for the factories otherwise multiple clients will have their own versions of the factories.

public interface I_Animal {
     
      public void makeSound();

}
public class Cat implements I_Animal {

      @Override
      public void makeSound() {
            System.out.println("Meaow");
      }

}
public class Dog implements I_Animal {

      @Override
      public void makeSound() {
            System.out.println("Bark");
      }

}
public class Factory {
     
      private static final Factory instance = new Factory();
     
      private Factory() {
            super();
      }

      public static Factory getInstance() {
            return instance;
      }
     
      public I_Animal getAnimal(String name) {
            if(name.equals("cat")) {
                  return new Cat();
            } else {
                  return new Dog();
            }
      }

}
public class MainClass {
     
      public static void main(String[] args) {
            I_Animal animal1 = Factory.getInstance().getAnimal("cat");
            animal1.makeSound();
            I_Animal animal2 = Factory.getInstance().getAnimal("dog");
            animal2.makeSound();
      }


}


Code link : https://github.com/sksumit1/DesignPatterns

No comments:

Post a Comment