Syed Sayem blog

Factory method pattern

Factory method pattern example

public interface Animal {
    <T> T create(Class<T> responseClass);
}
public class AnimalFactory implements Animal {

    @Override
    public <T> T create(Class<T> responseClass) {
        try {
            return responseClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new IllegalArgumentException(e);
        }
    }
}
public class Cat {

    public Dog catSound() {
        System.out.println("Meow");
        return new Dog();
    }
}
public class Dog {

    public void dogSound() {
        System.out.println("Wof");
    }

}
public class App {

    public static void main(String[] args) {

        Animal animal = new AnimalFactory();
        Cat cat = animal.create(Cat.class);
        cat.catSound();
        
        Dog dog = animal.create(Dog.class);
        dog.dogSound();
    }
}
comments powered by Disqus