适配器模式的适用:
你想使用一个已经存在的类,而它的接口不符合你的需求。
你想创建一个可以复用的类,该类可以与其他不相关的类或不可预见的类(即那些接口可能不一定兼容的类)协同工作。
你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配它们的接口,那么对象适配器可以适配它的父类接口(仅适用于对象Adapter)。
示例说明:
这个例子模拟了对一个特定组织系统——OrganizationAdaptee的适配。适配器OrganizationAdapter实现了适配接口IOrganization,从而使得客户端系统可以通过自己的接口IOrganization使用此组织系统——OrganizationAdaptee,而不需要耦合它的API。
package com.alex.designpattern.adapter;
import java.util.HashMap;
import java.util.Map;
import java.util.Map;
/** *//**
* 适配器模式
* <p>
* 将一个类的接口转换成客户希望的另外一个接口。 <br>
* Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
*
* @author <a href=" huqimailto:huqiyes@gmail.com">huqi</a>
* @serialData 2007
*/
public class Test ...{
* 适配器模式
* <p>
* 将一个类的接口转换成客户希望的另外一个接口。 <br>
* Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
*
* @author <a href=" huqimailto:huqiyes@gmail.com">huqi</a>
* @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);
}
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
// ...
}
// 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);
}
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;
}
}
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();
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");
}
}
Map result = adaptee.queryRole(String.valueOf(id));
return result.get("id") + ", " + result.get("type") + ", "
+ result.get("name");
}
}
本文转自胡奇 51CTO博客,原文链接:http://blog.51cto.com/huqicto/280901,如需转载请自行联系原作者