我正在阅读收集框架的优势,我发现了一个声明,即" Java Collections Framework可以使您从编写适配器对象或转换代码来连接API中可以使您无法理解。.....
[链接] http://docs.oracle.com/javase/tutorial/collections/intro/
我谷歌搜索并找到了一些适配器模式和其他内容..........但我想知道"适配器对象"。
任何人都可以解释......
我认为我有一个粗略的例子。假设您必须与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 Collections帮助的地方(对于此特定示例,java.util.List
)。使用Java的List
接口,开发人员可以简单地给出List<Mobile>
和List<Book>
,您可以在这些List
S上调用get(index)
或add(product)
,而无需任何适配器类。这是因为现在MobileList
和BookList
具有共同的方法名称和行为集。我认为这就是文档中所说的
通过促进无关API之间的互操作性
在这种情况下,无关的API为MobileList
和BookList
。
适配器模式用于当您想要两个不同的类带有不兼容接口的类别的类别时。/p>