适配器模式

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

缺省适配器模式为一个接口提供缺省实现,这样子类型可以从这个缺省实现进行扩展,而不必从原有接口进行扩展。适配器模式的用意是改变源角色接口形式,以便于与目标接口相兼容,缺省的适配器用意则是为了方便建立一个不平庸的适配器类而提供的一种平庸的实现。

适配器模式有类的适配器模式和对象的适配器模式:

  1. 类适配器模式使用继承的方式,是静态的定义方式;对象适配器模式使用组合的方式,是动态的定义方式;
  2. 类的适配器模式可以重定义源角色的部分行为,相当于子类覆盖父类的部分方法;对象的适配器需要定义源角色的子类来实现重定义,然后组合子类;当想要增加一些新的行为时使用对象的适配器模式很方便且可同时适用于所有的源角色;
  3. 对于对象适配器,一个适配器可以把不同的源适配到同一目标;

示例:

class Apple {
    public void getAColor(String str) {
        System.out.println("Apple color is: " + str);
    }
}
 
class Orange {
    public void getOColor(String str) {
        System.out.println("Orange color is: " + str);
    }
}
 
class AppleAdapter extends Apple {
    private Orange orange;
 
    public AppleAdapter(Orange orange) {
        this.orange = orange;
    }
 
    public void getAColor(String str) {
        orange.getOColor(str);
    }
}
 
public class TestAdapter {
    public static void main(String[] args) {
        Apple apple1 = new Apple();
        Apple apple2 = new Apple();
        apple1.getAColor("green");
 
        Orange orange = new Orange();
 
        AppleAdapter aa = new AppleAdapter(orange);
        aa.getAColor("red");
    }
}

多用聚合/组合,少用继承。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值