Factory method pattern example using Java 8 Lambda
@FunctionalInterface
public interface Animal {
String sound();
}
public enum AnimalFarm {
CAT(Cat::new),
DOG(Dog::new);
public final Animal factory;
AnimalFarm(Supplier<Animal> factory) {
this.factory = requireNonNull(factory).get();
}
}
public class Cat implements Animal{
@Override
public String sound() {
return ("Meow! Meow!");
}
}
public class Dog implements Animal{
@Override
public String sound() {
return ("Woof woof!");
}
}
public class App {
public static void main(String[] args) {
Animal dog = AnimalFarm.CAT.factory;
System.out.println(dog.sound());
Animal cat = AnimalFarm.DOG.factory;
System.out.println(cat.sound());
}
}