zoukankan      html  css  js  c++  java
  • 适配器模式【结构模式】

    适配器模式

    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);
        }
    }
    
  • 相关阅读:
    BZOJ3105: [cqoi2013]新Nim游戏 博弈论+线性基
    BZOJ3759: Hungergame 博弈论+线性基
    NOI模拟赛Day2
    期望dp BZOJ3450+BZOJ4318
    NOI模拟赛 Day1
    NOI模拟 热身赛T1
    【BZOJ4260】 Codechef REBXOR 可持久化Trie
    【BZOJ3673】&&【BZOJ3674】: 可持久化并查集 by zky 可持久化线段树
    【BZOJ3207】花神的嘲讽计划I 可持久化线段树/莫队
    【bzoj3527】[Zjoi2014]力 FFT
  • 原文地址:https://www.cnblogs.com/zhuxudong/p/10164180.html
Copyright © 2011-2022 走看看