读书笔记之设计模式(适配器模式)

适配器模式

适配器模式把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。

适配器模式又可以分为:
- 类适配器
- 对象适配器

类适配器

主要就是为某一个类而实现适配的一种模式, 把适配的类的API转换成为目标类的API。
- 目标(Target)角色:客户所期待的接口
- 需要被适配的类(Adaptee):需要适配的类
- 适配器(Adaper)角色:把原接口转换成目标接口

代码示例
目标接口
public interface Target{
    public void request();
}
需要被适配的类
public class Adaptee {
    public void specialRequest(){
        System.out.println("这是特殊请求!"); 
    }
}
适配器
public class Adapter extends Adaptee implements Target{
    @Override
    public void request(){
        this.specialRequest();
    }
}
测试类
public class TestClient {
    public static void main(String[] args) {  
        // 使用特殊功能类,即适配类  
        Target adapter = new Adapter();  
        adapter.request();  
    } 
}

因为Java是单继承的,所以这个适配器只能为Adaptee这个类服务,故称为类适配器。

对象适配器

与类适配器模式不同,对象适配器模式不是使用继承关系连接到Adaptee类,而是使用委派关系连接到Adaptee类。

代码示例
public interface Target{
    public void request();
}
需要被适配的类
public class Adaptee{
    public void specialRequest(){
        System.out.println("这是特殊请求!"); 
    }
}
适配器
public class Adapter implements Target{

    // 直接关联被适配类
    private Adaptee adaptee;

    public Adapter() {
        this.adaptee = new Adaptee();
    }

    @Override
    public void request() {
        adaptee.specialRequest();
    }
}
测试类
public class TestClient {
    public static void main(String[] args) {  

        // 使用特殊功能类,即适配类  
        Target adapter = new Adapter();   
        adapter.request();
    } 
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值