Monday, December 27, 2010

Factory Design Pattern in Java

Factory pattern comes into creational design pattern category, the main objective of the creational pattern is to instantiate an object and in Factory Pattern an interface is responsible for creating the object but the sub classes decides which class to instantiate. It is like the interface instantiate the appropriate sub-class depending upon the data passed. Here in this article we will understand how we can create an Factory Pattern in Java.

Now in the example that we are looking at for explaining the Factory Design Pattern is we are creating an object of Dog and Cat without calling the Dog or Cat class.

Mammal Class Code:

 class MammalsFactory {
public static Mammals getMammalObject(String name) {
if (name.equalsIgnoreCase("Cat")){
return new Cat();
} else {
return new Dog();
}
}
}
Now if you see this class, here we will be passing an
argument to the getMammalObject function based on the
argument passed we return the Mammals object of the class.

Abstract Class Code:
public abstract class Mammals {
public abstract String doWalking();
}
Here we have created an abstract class Mammals.
This class will be used by the Dog and Cat class.

Cat Class Code:
public class Cat extends Mammals {
public String doWalking() {
return "Cats has been Informed to perform";
}
}
Here we have created Cat class, this class extends
from Mammals class so it is understandable that
Cat needs to have the implementation for doWalking()
method.

Dog Class Code:
public class Dog extends Mammals {
public String doWalking() {
return "Dogs has been Informed to perform";
}
}
Here we have created Dog class, this class extends
from Mammals class so it is understandable that
Dog needs to have the implementation for doWalking()
method.

Factory Method Client Code:
public class FactoryClient {
public static void main(String args[]) {
MammalsFactory mf = new MammalsFactory();
System.out.println(mf.getMammalObject("Dog").doWalking());
}
}
Here if you see i want to create an object for Dog
class and for that we are not directly loading the
Dog class. Instead we are instantiated the object
for MammalsFactory class.





No comments:

Post a Comment