在Java中调用接口的特定实现类

问题描述 投票:-4回答:2

我正在尝试构建一个简单的API,其中我有一个接口AnimalService,其实现类是LionImplTigerImplElephantImplAnimalService有一种方法getHome()。 我有一个属性文件,其中包含我正在使用的动物类型,

animal=lion

因此,基于我正在使用的动物类型,当我调用我的API(来自getHome()AnimalService)时,应该执行特定实现类的getHome()方法。 我怎样才能做到这一点? 提前致谢。

java interface interface-implementation
2个回答
2
投票

您可以通过创建一个包含枚举的工厂类来实现此目的。

public static AnimalServiceFactory(){

    public static AnimalService getInstance() { // you can choose to pass here the implmentation string or just do inside this class
        // read the properties file and get the implementation value e.g. lion
        final String result = // result from properties
        // get the implementation value from the enum
        return AnimalType.getImpl(result);
    }

    enum AnimalType {
        LION(new LionImpl()), TIGER(new TigerImpl()), etc, etc;

        AnimalService getImpl(String propertyValue) {
            // find the propertyValue and return the implementation
        }
    }
}

这是一个高级代码,未针对语法错误等进行测试。


2
投票

您正在描述Java polymorphism的工作原理。以下是与您的说明相对应的一些代码:

AnimalService.java

public interface AnimalService {
    String getHome();
}

ElephantImpl.java

public class ElephantImpl implements AnimalService {
    public String getHome() {
        return "Elephant home";
    }
}

LionImpl.java

public class LionImpl implements AnimalService {
    public String getHome() {
        return "Lion home";
    }
}

TigerImpl.java

public class TigerImpl implements AnimalService {
    public String getHome() {
        return "Tiger home";
    }
}

PolyFun.java

public class PolyFun {
    public static void main(String[] args) {
        AnimalService animalService = null;

        // there are many ways to do this:
        String animal = "lion";
        if (animal.compareToIgnoreCase("lion")==0)
            animalService = new LionImpl();
        else if (animal.compareToIgnoreCase("tiger")==0)
            animalService = new TigerImpl();
        else if (animal.compareToIgnoreCase("elephant")==0)
            animalService = new ElephantImpl();

        assert animalService != null;
        System.out.println("Home=" + animalService.getHome());
    }
}

有关更多信息,请参阅https://www.geeksforgeeks.org/dynamic-method-dispatch-runtime-polymorphism-java/

© www.soinside.com 2019 - 2024. All rights reserved.