跳到主要內容

JAVA 泛型的基本運用

今日遇到一個case,剛好適合運用泛型,因此紀錄一下。
假設情境是這樣的:
class A 要實作加密跟解密兩個method,然後會使用到物件 dto A,
class B 也要實作加密跟解密兩個method,然後會使用到物件 dto B,

清楚地,因為兩個class都會實作到相同的method,但必須使用到專屬自己要用的物件(dto),所以這邊可以使用泛型(T)來假裝欲套用的型別來給介面使用.後續該物件在實作時則帶入欲使用的dto即可.


 public interface Vehicle<T> {  
      public T show(T other);  
      public List<T> shows(List<T> others);  
 }  

 public class ACar implements Vehicle<Adto>{  
      @Override  
      public Adto show(Adto other) {  
           System.out.println(other.getName());  
           return other;  
      }  
      @Override  
      public List<Adto> shows(List<Adto> others) {  
           for(Adto adto : others) {  
                System.out.println(adto.getName());  
           }  
           return null;  
      }  
 }  

 public class Adto {  
      String name;  
      public String getName() {  
           return name;  
      }  
      public void setName(String name) {  
           this.name = name;  
      }  
 }  

 public class BCar implements Vehicle<Bdto>{  
      @Override  
      public Bdto show(Bdto other) {  
           System.out.println(other.getName());  
           return null;  
      }  
      @Override  
      public List<Bdto> shows(List<Bdto> others) {  
           for(Bdto adto : others) {  
                System.out.println(adto.getName());  
           }  
           return null;  
      }  
 }  

 public class Bdto {  
      String name;  
      public String getName() {  
           return name;  
      }  
      public void setName(String name) {  
           this.name = name;  
      }  
 }  

 public class TestVehicle {  
      @Test  
      public void test(){  
           Adto adto = new Adto();  
           adto.setName("aa");  
           ACar aCar = new ACar();  
           aCar.show(adto);  
           Bdto bdto = new Bdto();  
           bdto.setName("bb");  
           BCar bCar = new BCar();  
           bCar.show(bdto);  
      }  
 }  

留言