2017-12-28 12 views
-4

私はインターフェイスがAnimalServiceで実装クラスがLionImpl,TigerImplElephantImplであるシンプルなAPIを構築しようとしています。
AnimalServiceは、方法getHome()を有する。
そして私は、だから私は私のAPI(AnimalServiceからgetHome())を呼び出すときに私は、使用していた動物の種類に基づいて Javaのインターフェイスの特定の実装クラスを呼び出す

、などの
animal=lion 

を使用して私は動物の種類が含まれているプロパティファイルを持っています特定の実装クラスのgetHome()メソッドを実行する必要があります。

どうすれば実現できますか?

ありがとうございます。

答えて

2

これは、列挙型を格納する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 polymorphism作品記述しているなど

2

構文エラーのためにテストされていない、高レベルのコードです。ここではあなたの説明に対応していくつかのコードは次のとおりです。

AnimalService.java

public interface AnimalService { 
    String getHome(); 
} 

ElephantImpl.java

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

LionImpl.java

詳細については、0

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/

を見ます
関連する問題