码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式之适配器模式 Adapter

时间:2017-09-04 12:01:41      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:his   ace   ext   test   分享   sys   nts   handle   模式   

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

技术分享

定义与角色

技术分享

技术分享

工作场景

技术分享

 

代码实现

 

技术分享
/**
 * 被适配的类--相当于键盘
 * @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

 

设计模式之适配器模式 Adapter

标签:his   ace   ext   test   分享   sys   nts   handle   模式   

原文地址:http://www.cnblogs.com/qingdaofu/p/7472713.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!