适配器模式【结构模式】

适配器模式

Convert the interface of a class into another interface clients except.
Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
将一个类的接口转换为另一个客户端所期望的接口。
适配器允许由于接口不兼容而无法一起工作的两个类可以协同工作。
public class Adapter {
    /**
     * 适配器模式:
     * Convert the interface of a class into another interface clients except.
     * Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
     * 将一个类的接口转换为另一个客户端所期望的接口。
     * 适配器允许由于接口不兼容而无法一起工作的两个类可以协同工作。
     */
    @Test
    public void all() {
        // 需要适配的旧接口实现
        final OldPhone oldPhone = new OldPhone();
        final String phone = oldPhone.getPhones().get(PhoneType.SELF);

        // 适配新旧接口的适配器
        final PhoneAdapter adapter = PhoneAdapter.builder().phone(oldPhone).build();
        // 工作在新接口环境下
        final String selfPhone = adapter.getSelfPhone();
        assertEquals(phone, selfPhone);
    }
}

enum PhoneType {
    SELF, WORK;
}

/**
 * 1)需要适配的目标接口
 */
interface IPhone {
    Map<PhoneType, String> getPhones();
}

/**
 * 2)旧接口的具体实现
 */
class OldPhone implements IPhone {
    private final Map<PhoneType, String> phones = Map.of(PhoneType.SELF, "666", PhoneType.WORK, "123");

    @Override
    public Map<PhoneType, String> getPhones() {
        return phones;
    }
}

/**
 * 3)客户端期望的接口规范
 */
interface PhoneSRP {
    String getSelfPhone();

    String getWorkPhone();
}

/**
 * 4)将旧接口适配为客户端期望接口的适配器,适配器持有旧接口的实例
 */
@Builder
class PhoneAdapter implements PhoneSRP {
    private final IPhone phone;

    @Override
    public String getSelfPhone() {
        return phone.getPhones().get(PhoneType.SELF);
    }

    @Override
    public String getWorkPhone() {
        return phone.getPhones().get(PhoneType.WORK);
    }
}

猜你喜欢

转载自www.cnblogs.com/zhuxudong/p/10164180.html
今日推荐