2014-02-06 58 views

回答

2

我想我有一個粗糙的例子。假設你必須使用2個API--其中一個涉及手機,另一個涉及書本。說移動API開發人員爲您提供這個API:

public class MobileList { 
    private Mobile[] mobiles; 
    //other fields 

    public void addMobileToList(Mobile mobile) { 
     //some code to add mobile 
    } 

    public void getMobileAtIndex(int index) { 
     return mobiles[index]; 
    } 

    //maybe other methods 
} 

並說書API開發人員爲您提供這個API:

public class BookList { 
    private Book[] books; 
    //other fields 

    public void addBook(Book book) { 
     //some code to add book 
    } 

    public Book[] getAllBooks() { 
     return books; 
    } 

} 

現在,如果你的代碼塊只能以下的產品「界面:

interface Products { 
    void add(Product product); 
    Product get(int index); 
} 

你必須編寫實現你需要的接口下「適配器」的對象:

class MobileListAdapter implements Products { 
    private MobileList mobileList; 

    public void add(Product mobile) { 
     mobileList.addMobileToList(mobile); 
    } 

    public Product get(int index) { 
     return mobileList.getMobileAtIndex(index); 
    } 
} 

class BookListAdapter implements Products { 
    private BookList bookList; 

    public void add(Product book) { 
     bookList.add(book); 
    } 

    public Product get(int index) { 
     return bookList.getAllBooks()[index]; 
    } 
} 

請注意,每個這樣的Product API也可以具有各種方法和各種方法以及。如果你的代碼是期待僅在Products接口工作,你必須寫這樣的「適配器」爲每一個新Product該走了進來。

這就是Java集合幫助(java.util.List這個具體的例子)。使用Java的List接口,開發人員可以簡單地發出List<Mobile>List<Book>,您可以簡單地在這些List上調用get(index)add(product),而不需要任何適配器類。這是因爲現在MobileListBookList有一套共同的方法名稱和行爲。我認爲這是在文檔中的意思,它說

通過促進無關的API

在這種情況下,不相關的API是MobileListBookList之間的互操作性。