设计模式之适配器模式 Adapter

从现在开始,将转入设计模式中的结构型模式

定义与角色

工作场景

 

代码实现

 

/**
 * 被适配的类--相当于键盘
 * @author bzhx
 * 2017年3月10日
 */
public class Adaptee {

    public void request(){
        System.out.println("可以完成客户请求的需要的功能");
    }
    
}
Adaptee类
public interface Target {
    void handleReq();
}
Target 接口
/**
 * 适配器(类适配器方式)--相当于usb转接器
 * @author bzhx
 * 2017年3月10日
 */
public class Adapter extends Adaptee implements Target{

    @Override
    public void handleReq() {
        super.request();
    }

}
适配器类Adapter
/**
 * 适配器(对象适配器,使用了组合方式跟被适配对象整合)--相当于usb转接器
 * @author bzhx
 * 2017年3月10日
 */
public class Adapter2 implements Target{

    private Adaptee adaptee;
    
    @Override
    public void handleReq() {
        adaptee.request();
    }

    public Adapter2(Adaptee adaptee) {
        super();
        this.adaptee = adaptee;
    }
    
}
适配器类 Adapter2
/**
 * 客户端类----相当于笔记本,只有usb接口
 * @author bzhx
 * 2017年3月10日
 */

public class Client {

    public void test1(Target t){
        t.handleReq();
    }
    
    public static void main(String[] args) {
        Client c = new Client();
        Adaptee a = new Adaptee();
        
        Target t = new Adapter();
        c.test1(t);
    }
}
调用1
/**
 * 客户端类----相当于笔记本,只有usb接口
 * @author bzhx
 * 2017年3月10日
 */

public class Client2 {

    public void test1(Target t){
        t.handleReq();
    }
    
    public static void main(String[] args) {
        Client2 c = new Client2();
        Adaptee a = new Adaptee();
        
        Target t = new Adapter2(a);
        c.test1(t);
    }
}
调用2

 

posted @ 2017-09-04 11:18  皈依之路  阅读(171)  评论(0编辑  收藏  举报