我正在阅读集合框架的优点,我发现了一个声明,“Java集合框架可以让您免于编写适配器对象或转换代码来连接API。”我无法理解这一点......什么是适配器对象模式?
[链接] http://docs.oracle.com/javase/tutorial/collections/intro/
我GOOGLE了一下,发现了一些适配器模式和其他的东西.........但我想知道“适配器对象”。
任何一个可以解释......
我正在阅读集合框架的优点,我发现了一个声明,“Java集合框架可以让您免于编写适配器对象或转换代码来连接API。”我无法理解这一点......什么是适配器对象模式?
[链接] http://docs.oracle.com/javase/tutorial/collections/intro/
我GOOGLE了一下,发现了一些适配器模式和其他的东西.........但我想知道“适配器对象”。
任何一个可以解释......
我想我有一个粗糙的例子。假设你必须使用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)
,而不需要任何适配器类。这是因为现在MobileList
和BookList
有一套共同的方法名称和行为。我认为这是在文档中的意思,它说
通过促进无关的API
在这种情况下,不相关的API是MobileList
和BookList
之间的互操作性。
适配器模式使用时,你希望两个不同的班级,不兼容的接口工作together.See此例如http://javapapers.com/design-patterns/adapter-pattern/