Factory design pattern


  • We create objects without exposing the creation logic to the client and refer to newly created object using a common interface.
  • In simple words if we have super and sub classes , and based on data provided we have to return the object of one of the sub classes , we use factory pattern.
  • The basic principal behind this pattern is that , at run time we get an object of similar type based on the parameter we passed.
  • If object creation code is spread in whole application, and you need to change the creation of object creation then you need to go in each and every place to make necessary changes.

facade

We have different animals like Duck , Dog and Lion which extends Animal.

abstract Class Animal 
{
  abstract String speak();
}
class Duck
{
 string speak()
 {
  return "Quack quack";
 }
}
class Dog
{
 string speak()
 {
  return "Bark bark";
 }
}

class Roar
{
 string speak()
 {
  return "Roar roar";
 }
}

class AnimalFactory 
{
 public Animal getAnimal(String animalType)
 {
   Animal animal = null;
   if("dog".equals(animalType))
       animal = new Dog();
   if("duck".equals(animalType))
       animal = new Duck();
   if("lion".equals(animalType))
       animal = new Lion();
 }
}
class SpeakAnimals 
{
 AnimalFactory animalFactory = new AnimalFactory();
 Animal animal = animalFactory.getAnimal(“Dog”);
 animal.speak();
}


Now you can check above conditions with this example.