前言

Github:https://github.com/yihonglei/java-design-patterns

一 适配器模式作用

将一个类的接口转换为客户希望的另外一个接口,使得不兼容的接口兼容在一起。

二 应用场景

1)当想使用一个已经存在的类,但是类的接口不符合需求;

2)创建一个可以复用的类,使得该类可以与其他不相关的类或不可预见的类(即那些接口可能不一定兼容的类)协同工作;

3)不能对子类接口进行匹配时,可以通过适配器模式匹配其父类的接口;

三 UML图

适配器模式静态类图:

四 参与对象

1)Adaptee

定义一个已经存在的接口,这个接口需要适配。

2)Adapter

定义Client使用的与特定领域相关的接口,目标接口,也可称为标准接口。

3)ConcreteAdapter

适配器,对Adaptee接口与Adapter接口进行适配。

4)Client

与符合Adapter接口对象协同。

五 适配器模式实战

Adaptee

package com.jpeony.design.patterns.adapter.demo1;

/**
 * 已经存在,具有特殊功能,但是不符合我们已经存在的标准接口
 *
 * @author yihonglei
 */
public class Adaptee {
    public void adapteeMethod() {
        System.out.println("将要被适配的类");
    }
}

Adapter

package com.jpeony.design.patterns.adapter.demo1;

/**
 * @author yihonglei
 */
public interface Adapter {
    void adapteeMethod();

    void adapterMethod();
}

ConcreteAdapter

package com.jpeony.design.patterns.adapter.demo1;

/**
 * 适配器: 将被适配类Adaptee与目标接口Adapter进行适配
 *
 * @author yihonglei
 */
public class ConcreteAdapter implements Adapter {

    private Adaptee adaptee;

    public ConcreteAdapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void adapteeMethod() {
        adaptee.adapteeMethod();
    }

    @Override
    public void adapterMethod() {
        System.out.println("目标接口的方法");
    }
}

Client

package com.jpeony.design.patterns.adapter.demo1;

/**
 * @author yihonglei
 */
public class Client {
    public static void main(String[] args) {
        // 被适配器类
        Adaptee adaptee = new Adaptee();
        // 标准接口
        Adapter adapter = new ConcreteAdapter(adaptee);
        // Adaptee 与 Adapter两个无关的类协同工作
        adapter.adapteeMethod();
        adapter.adapterMethod();
    }
}

运行结果

更多推荐