适配器模式

来源:互联网 发布:网络直播加速 编辑:程序博客网 时间:2024/05/17 03:51

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

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

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

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

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

 

0 0
原创粉丝点击