Factory
method design pattern
This is an
extension of Factory design pattern. Let suppose even though different objects
are created and returned based on the factory arguments. What if there is a
generic pre/post processing that’s required before returning the object from
the factory.
public interface I_Animal {
public void makeSound();
}
public class Cat implements I_Animal {
@Override
public void makeSound() {
System.out.println("Meaow !! I just had food");
}
}
public class Dog implements I_Animal {
@Override
public void makeSound() {
System.out.println("Bark !! I just had food");
}
}
public class Factory {
private static final Factory instance = new Factory();
private Factory() {
super();
}
public static Factory
getInstance() {
return instance;
}
private I_Animal
getAnimal(String name) {
if(name.equals("cat")) {
return new Cat();
}
else {
return new Dog();
}
}
public I_Animal
factoryMethod(String name) {
I_Animal
animal = getAnimal(name);
System.out.println("Food served to "+name+" "+animal.getClass().getCanonicalName());
return animal;
}
}
public class MainClass {
public static void main(String[]
args) {
I_Animal
animal1 = Factory.getInstance().factoryMethod("cat");
animal1.makeSound();
I_Animal
animal2 = Factory.getInstance().factoryMethod("dog");
animal2.makeSound();
}
}
Code link : https://github.com/sksumit1/DesignPatterns
Code link : https://github.com/sksumit1/DesignPatterns
No comments:
Post a Comment