簡體   English   中英

Java中調用接口的具體實現類

[英]Calling specific implementation classes of an Interface in Java

我正在嘗試構建一個簡單的 API,其中我有一個AnimalService接口,它的實現類是LionImplTigerImplElephantImpl
AnimalService有一個方法getHome()
我有一個屬性文件,其中包含我正在使用的動物類型,

animal=lion

因此,基於我現在用的,當我(叫我的API動物類型getHome()AnimalService ),具體的實現類的getHome()方法應該被執行。

我怎樣才能做到這一點?

提前致謝。

您可以通過創建一個包含枚舉的 Factory 類來實現這一點,例如

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
        }
    }
}

這是一個高級代碼,未測試語法錯誤等。

您正在描述Java 多態性的工作原理。 以下是與您的描述相對應的一些代碼:

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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM