我正在閱讀集合框架的優點,我發現了一個聲明,「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/