擴充卡模式的适用:
你想使用一個已經存在的類,而它的接口不符合你的需求。
你想建立一個可以複用的類,該類可以與其他不相關的類或不可預見的類(即那些接口可能不一定相容的類)協同工作。
你想使用一些已經存在的子類,但是不可能對每一個都進行子類化以比對它們的接口,那麼對象擴充卡可以适配它的父類接口(僅适用于對象Adapter)。
示例說明:
這個例子模拟了對一個特定組織系統——OrganizationAdaptee的适配。擴充卡OrganizationAdapter實作了适配接口IOrganization,進而使得用戶端系統可以通過自己的接口IOrganization使用此組織系統——OrganizationAdaptee,而不需要耦合它的API。
package com.alex.designpattern.adapter;
import java.util.HashMap;
import java.util.Map;
/** *//**
* 擴充卡模式
* <p>
* 将一個類的接口轉換成客戶希望的另外一個接口。 <br>
* Adapter模式使得原本由于接口不相容而不能一起工作的那些類可以一起工作。
*
* @serialData 2007
*/
public class Test ...{
public static void main(String[] args) ...{
Test test = new Test();
IOrganization org = new OrganizationAdapter();
String result = test.genericClientCode(org);
System.out.println("Using client, get result: " + result);
}
private String genericClientCode(IOrganization org) ...{
// We assume this function contains client-side code that only
// knows about IOrganization.
return org.getRole(4);
// other calls to IOrganization go here
// ...
}
interface IOrganization ...{
public String getRole(int id);
class OrganizationAdaptee ...{
public Map<String, String> queryRole(String id) ...{
System.out.println("Query a Role in the Adaptee Organization, id: "
+ id);
// query using id ... get result
Map<String, String> map = new HashMap<String, String>();
map.put("id", id);
map.put("name", "huqi");
map.put("type", "human");
return map;
class OrganizationAdapter implements IOrganization ...{
private OrganizationAdaptee adaptee = new OrganizationAdaptee();
public String getRole(int id) ...{
Map result = adaptee.queryRole(String.valueOf(id));
return result.get("id") + ", " + result.get("type") + ", "
+ result.get("name");
本文轉自胡奇 51CTO部落格,原文連結:http://blog.51cto.com/huqicto/280901,如需轉載請自行聯系原作者