实现工厂的最佳方式,如果没有,切换 [英] The best way to implement Factory without if, switch

查看:131
本文介绍了实现工厂的最佳方式,如果没有,切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过许多方法来实现Java中的Factory模式,但仍然找不到一个完美的方法,如果/ switch plus不使用反射,则不会受到影响。
我发现最好的之一是Tom Hawtin在这里的答案: http://stackoverflow.com/a/3434505/ 1390874



但是我最关心的是在内存中存储一​​个匿名类的HashMap。



<问题是除了Tom Hawtin的答案之外,人们还在使用 Class.newInstance()做什么?
这将避免我们在内存中存储不必要的匿名类? Plus代码将会更加干净。



它将如下所示:

  class MyFactory {
private static final Map< String,Class> factoryMap =
Collections.unmodifiableMap(new HashMap< String,Class>(){{
put(Meow,Cat.class);
put(Woof,Dog.class) ;
}});

public Animal createAnimal(String action){
return(Animal)factoryMap.get(action).newInstance();
}
}


解决方案

你正在使用java 8,你可以这样设置一个枚举

  enum AnimalFarm {
喵(Cat :: new),
Woof(Dog :: new);

public final供应商<动物>厂;
private AnimalFarm(Supplier< Animal> factory){
this.factory = requireNonNull(factory);
}
}

...

动物狗= AnimalFarm.valueOf(Woof)。factory.get();

你甚至可以拥有枚举 code>供应商< Animal> 然后执行 AnimalFarm.valueOf(Meow)。get();


I was looking through many approaches to implement a Factory pattern in Java and still couldn't find a perfect one which doesn't suffer from both if/switch plus doesn't use reflection. One of the best that I found was inside Tom Hawtin's answer here: http://stackoverflow.com/a/3434505/1390874

But my biggest concern is that it stores a HashMap of Anonymous classes in a memory.

The question is what do people think about using Class.newInstance() in addition to Tom Hawtin's answer? This will avoid us from storing unnecessary anonymous classes in memory? Plus code will be more clean.

It will look something like this:

class MyFactory {
    private static final Map<String,Class> factoryMap =
        Collections.unmodifiableMap(new HashMap<String,Class>() {{
            put("Meow", Cat.class);
            put("Woof", Dog.class);
    }});

    public Animal createAnimal(String action) {
        return (Animal) factoryMap.get(action).newInstance();
    }
}

解决方案

If you are using java 8, you can set up an enum like this:

enum AnimalFarm {
    Meow(Cat::new),
    Woof(Dog::new);

    public final Supplier<Animal> factory;
    private AnimalFarm(Supplier<Animal> factory) {
        this.factory = requireNonNull(factory);
    }
}

......

Animal dog = AnimalFarm.valueOf("Woof").factory.get();

You could even have the enum implement Supplier<Animal> and then do AnimalFarm.valueOf("Meow").get();.

这篇关于实现工厂的最佳方式,如果没有,切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆