什么是适配器对象模式?

时间:2014-02-06 09:09:15

标签: java collections

我正在阅读集合框架的优点,我发现一条声明“Java Collections Framework让你无需编写适配器对象或转换代码来连接API。”我无法理解这一点......

[链接] http://docs.oracle.com/javase/tutorial/collections/intro/

我用谷歌搜索并发现了一些适配器模式和其他东西.........但我想了解“适配器对象”。

任何人都可以解释......

2 个答案:

答案 0 :(得分: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>,您只需在这些get(index)上调用add(product)List即可不需要任何适配器类。这是因为现在MobileListBookList具有一组共同的方法名称和行为。我认为这就是文档中的含义

  

促进不相关API之间的互操作性

此案例中不相关的API为MobileListBookList

答案 1 :(得分:1)

适配器模式用于当您希望两个具有不兼容接口的不同类一起工作时。请参阅此示例http://javapapers.com/design-patterns/adapter-pattern/