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){

        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);  
  • 1
    \$\begingroup\$ Not an answer to your question, just a remark regarding newInstance before you enter real life with such mis-information. Your teacher was right a few years ago (I think prior to java 5) that newInstance is relatively costly. Nowadays, this is not true anymore. So, please just regard that as "set rules for your homework" but not as real info to take into your future projects. ;-) \$\endgroup\$ – mtj Dec 22 '16 at 10:29
  • \$\begingroup\$ hi mtj, tnx for your response. I had a discussion with her about it. We could not found any reference to your claim. Can you please give us a broader explanation for the reason or to provide us with a reference? \$\endgroup\$ – Arigatonic Dec 26 '16 at 8:29
  • 1
    \$\begingroup\$ Check your favorite search engine for reflection performance, and be sure to only regard results from the last 5 years... One example where somebody bothered to actually do some benchmarks: buzdin.lv/2011/01/is-java-reflection-really-slow.html \$\endgroup\$ – mtj Dec 26 '16 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.