2014-02-06 152 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之间的互操作性。