2017-12-28 33 views
-4

인터페이스가 AnimalService이고 구현 클래스가 LionImpl, TigerImpl, ElephantImpl 인 간단한 API를 작성하려고합니다.
AnimalService은 방법이 getHome()입니다.
그리고 나는 내가 좋아하는 을 사용하고 동물의 종류를 포함하는 속성 파일을 가지고,Java에서 인터페이스의 특정 구현 클래스 호출하기

animal=lion 

은 그래서, 내가 사용하고있는 동물의 종류에 따라 내 API (AnimalService에서 getHome())를 호출하면, 특정 구현 클래스의 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 자세한 내용

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()); 
    } 
} 

public class TigerImpl implements AnimalService { 
    public String getHome() { 
     return "Tiger home"; 
    } 
} 
참조 https://www.geeksforgeeks.org/dynamic-method-dispatch-runtime-polymorphism-java/