23种经典设计模式的java实现_2_适配器模式

来源:互联网 发布:石青软件被骗 编辑:程序博客网 时间:2024/04/30 07:01

适配器模式的适用:

你想使用一个已经存在的类,而它的接口不符合你的需求。

你想创建一个可以复用的类,该类可以与其他不相关的类或不可预见的类(即那些接口可能不一定兼容的类)协同工作。

你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配它们的接口,那么对象适配器可以适配它的父类接口(仅适用于对象Adapter)。

示例说明:

这个例子模拟了对一个特定组织系统——OrganizationAdaptee的适配。适配器OrganizationAdapter实现了适配接口IOrganization,从而使得客户端系统可以通过自己的接口IOrganization使用此组织系统——OrganizationAdaptee,而不需要耦合它的API。

package com.alex.designpattern.adapter;

import java.util.HashMap;
import java.util.Map;

/**
 * 适配器模式
 * <p>
 * 将一个类的接口转换成客户希望的另外一个接口。 <br>
 * Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
 * 
 * 
@author <a href="mailto: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);
    }


    
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");
    }

}