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

前端 未结 10 1484
走了就别回头了
走了就别回头了 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:00

    I haven't tried this, but could with create a Map with "Meow", etc as keys and (say) Cat.class as value.

    Provide a static instance generation via an interface and call as

    Animal classes.get("Meow").getInstance()
    

提交回复
热议问题