Here's my implementation of Generic Factory using Function library.
It was created using Function library because I understand that the newInstance
method is costly (as it uses reflections in the background[not sure about it]) and mostly because our teacher have decided :-).
I wonder about how can it be more generic from the ARGS perspective. As you can understand: this implementation limits the Factory only to one type of functions (ones with Void args in this Main example).
I will be happy to hear any opinions about this or any other aspect of the code.
import java.util.HashMap;
import java.util.function.Function;
public class Factory<Key, Type, Args> {
HashMap<Key, Function<Args, ? extends Type>> map;
public Factory(){
map = new HashMap<>();
}
public void add(Key key, Function<Args, ? extends Type> func){
map.put(key, func);
};
public Type create (Key key, Args args){
return map.get(key).apply(args);
}
}
class Pizza{
public Object bake(Void v){
System.out.println("baking");
return new Object();
}
public static Pizza getInst(Void v) {
return (new Pizza());
}
}
public class Main {
public static void main(String[] args) {
Factory<String, Object, Void> pizzaFactory = new Factory<>();
pizzaFactory.add("Pizza", Pizza::getInst);
Pizza slice = (Pizza)pizzaFactory.create("Pizza", null);
pizzaFactory.add("bake", slice::bake);
pizzaFactory.create("bake", null);
}
}