Creating a factory method in Java that doesn't rely on if-else

前端 未结 10 1501
走了就别回头了
走了就别回头了 2020-11-30 23:37

Currently I have a method that acts as a factory based on a given String. For example:

public Animal createAnimal(String action)
{
    if (action.equals(\"M         


        
10条回答
  •  心在旅途
    2020-12-01 00:12

    And what do people think about using Class.newInstance() inside 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:

    private static final Map factoryMap =
        Collections.unmodifiableMap(new HashMap() {{
            put("Meow", Cat.class);
            put("Woof", Dog.class);
    }});
    
    public Animal createAnimal(String action) {
        return (Animal) factoryMap.get(action).newInstance();
    }
    

提交回复
热议问题