适配器模式

适配器模式:将一个类的接口,转换成另一个类的接口。让原本不兼容的类可以使用(这里的接口表示某种意义上的抽象)。
适配器模式分为两种:

  • 类适配器模式:适配者和适配器为继承的关系,适配器在提供目标的行为时,是通过继承适配者的行为去表现。
  • 对象适配器模式:适配者和适配器为组合的关系,适配器在提供目标的行为时,是通过委托给适配者。

UML

说明

适配器模式的适用场景是针对客户需要某种类型的接口Target,而目前却只有另一种的接口Adaptee时,通过适配者AdapterAdaptee转换成Target。 其中类适配器模式只能限于Target为接口的情况(因为Java不支持多继承),而对象适配器模式在Target是接口或类的情况下都能使用(因为适配者和适配器是组合关系)。

代码

Client:
public class ChinaMadeDevice {

    private ChinaPower power;

    public ChinaMadeDevice(ChinaPower power){
        this.power = power;
    }

    public void work(){
        power.chinaOutput();
        System.out.println("Device Works");
    }
}

ChinaMadeDevice作为一个客户,表示一个国产的电器,它需要依赖国标的电压才能正常工作。

Target:
public interface ChinaPower {

    int chinaOutput();
}

ChinaPower是一个国标电源,提供符合国标的电压输出。

Adaptee:
public class USAPower {

    public int usaOutput(){
        System.out.println("USA Power output 120V");
        return 120;
    }
}

USAPower假设你正在美国旅游,目前的电源条件是美标的。那么为了你的设备能正常使用,你就需要适配器。

Adapter:
  • 类适配器模式的实现:
public class USAPowerClassAdapter extends USAPower implements ChinaPower {

    public int chinaOutput() {
        usaOutput();
        System.out.println("Start Adapt, Power Up");
        return 220;
    }

}

适配器继承适配者对象,并实现了目标接口,在实现目标接口的方法时,通过==继承而来的行为并适配==,达到对外表现为目标接口的目的。

  • 对象适配器模式的实现:
public class USAPowerObjectAdapter implements ChinaPower {

    private USAPower power;

    public USAPowerObjectAdapter(USAPower power){
        this.power = power;
    }

    public int chinaOutput() {
        System.out.println("Start output ele, delegate to USAPower");
        power.usaOutput();
        System.out.println("Adapter USA Power, Power up");
        return 220;
    }
}

适配器对象实现了目标对象接口,并拥有一个适配者对象,在实现目标对象的方法时,通过==委托给适配者==对象并适配,达到达到对外表现为目标接口的目的。

测试代码:
public class AdapterTest {

    public static void main(String[] args){
        testClassAdapter();

        testObjectAdapter();
    }

    protected static void testClassAdapter(){
        System.out.println("Class Adapter");
        new ChinaMadeDevice(new USAPowerClassAdapter()).work();
    }

    protected static void testObjectAdapter(){
        System.out.println("Object Adapter");
        new ChinaMadeDevice(new USAPowerObjectAdapter(new USAPower())).work();
    }
}
输出结果:
> Class Adapter
USA Power output 120V
Start Adapt, Power Up
Device Works
Object Adapter
Start output ele, delegate to USAPower
USA Power output 120V
Adapter USA Power, Power up
Device Works

上述代码见Github

01-03 11:48
查看更多