Friday 27 September 2013

Factory Design Pattern - Implementation



Click here to watch in Youtube : https://www.youtube.com/watch?v=q9p-E19JFlA

Click the below Image to Enlarge
Factory Design Pattern - Implementation - Class Diagram























Animal.java

public interface Animal
{
public String speak();
}


Dog .java

public class Dog implements Animal
{

@Override
public String speak()
{
return "Bark Bark Bark";
}

}


Duck.java

public class Duck implements Animal
{

@Override
public String speak()
{
return "Quack Quack Quack";
}

}

Lion.java

public class Lion implements Animal
{

@Override
public String speak()
{
return "Roar";
}

}

AnimalFactory.java

public class AnimalFactory
{
public Animal getAnimal( String animalType )
{
Animal animal = null;
if( "dog".equals(animalType) )
{
animal = new Dog();
}
else if( "duck".equals(animalType) )
{
animal = new Duck();
}
else if( "lion".equals(animalType) )
{
animal = new Lion();
}
return animal;
}
}


Client.java

public class Client
{

public static void main( String[] args )
{
AnimalFactory animalFactory = new AnimalFactory();
Animal animal = null;
String speakSound = null;
animal = animalFactory.getAnimal("dog");
System.out.println("Animal Type : "+animal.getClass().getName());
speakSound = animal.speak();

System.out.println("dog speak : "+speakSound);
System.out.println();

animal = animalFactory.getAnimal("duck");
System.out.println("Animal Type : "+animal.getClass().getName());
speakSound = animal.speak();

System.out.println("duck speak : "+speakSound);
System.out.println();

animal = animalFactory.getAnimal("lion");
System.out.println("Animal Type : "+animal.getClass().getName());
speakSound = animal.speak();

System.out.println("lion speak : "+speakSound);

}

}

Output

Animal Type : Dog
dog speak : Bark Bark Bark

Animal Type : Duck
duck speak : Quack Quack Quack

Animal Type : Lion
lion speak : Roar

No comments:

Post a Comment