• 设计模式-适配器模式


    1、定义

      适配器模式将一个类的接口,转换成客户期望的另外一个接口。使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。

    2、实现方式

    1)通过组合方式实现:

    /**
     * 目标接口
     */
    public interface ThreePlugIf {
        /**
         * 使用三相电流供电
         */
        void powerWithThree();
    }

    客户端

    package com.cn.shejimoshi.shipeiqimoshi;
    
    /**
     * 客户端
     */
    public class NoteBook {
    
        private ThreePlugIf threePlugIf;
    
        public NoteBook(ThreePlugIf threePlugIf) {
            this.threePlugIf = threePlugIf;
        }
    
        /**
         * 使用插座充电
         */
        public void charge(){
            threePlugIf.powerWithThree();
        }
    }

    被适配的类

    package com.cn.shejimoshi.shipeiqimoshi;
    
    /**
     *被适配类
     */
    public class GBTwoPlug {
    
        public void powerWithTwo(){
            System.out.println("使用二相电流供电");
        }
    }

    适配器

    package com.cn.shejimoshi.shipeiqimoshi;
    
    /**
     * 适配器
     */
    public class TwoPlugAdapter implements ThreePlugIf{
    
        private GBTwoPlug gbTwoPlug;
    
        public TwoPlugAdapter(GBTwoPlug gbTwoPlug) {
            this.gbTwoPlug = gbTwoPlug;
        }
    
        public void powerWithThree() {
            System.out.println("转换--通过组合方式实现适配器模式");
            gbTwoPlug.powerWithTwo();
        }
    }

      说明:适配器将GBTwoPlug 类的接口powerWithTwo,转换成客户NoteBook 期望的另外一个接口powerWithThree。使得原本不兼容的NoteBook GBTwoPlug类可以在一起工作。

    2)通过继承方式实现

    适配器修改为:

    package com.cn.shejimoshi.shipeiqimoshi;
    
    public class TwoPlugAdaterExtend extends GBTwoPlug implements ThreePlugIf {
    
        public void powerWithThree() {
            System.out.println("转换--通过继承方式实现适配器模式");
            powerWithTwo();
        }
    }

    测试方法

    public class NoteBookTest {
    
        @Test
        public void charge(){//测试组合方式
    
            GBTwoPlug gbTwoPlug=new GBTwoPlug();
            ThreePlugIf threePlugIf=new TwoPlugAdapter(gbTwoPlug);
            NoteBook noteBook=new NoteBook(threePlugIf);
            noteBook.charge();
        }
    
        @Test
        public void charge2(){//测试继承方式
            ThreePlugIf threePlugIf=new TwoPlugAdaterExtend();
            NoteBook noteBook=new NoteBook(threePlugIf);
            noteBook.charge();
        }
    }

    3、组合与继承实现方式的比较

    • 组合方式:可以基于面向接口编程适配多个被适配类,比如将适配器中的GBTwoPlug 域改成某个接口,建议使用组合方式
    • 继承方式:由于只能继承一个父类,故只能适配一个被适配类

    4、适配器的作用

    • 将目标类和适配者类解耦,通过引入一个适配器类重用现有的是配者类,而无需修改原有代码
    • 通过适配器,客户端可以调用同一接口,因而对客户端来说是透明的

    写在最后:

     设计模式是一种经验总结、编程思想,拒绝代码的迷惑。

     一种设计模式的代码变体可以有很多,但万变不离其宗。

  • 相关阅读:
    水晶报表开发
    ASP.NET页面刷新方法总结
    DataList获取当前ID
    flexviewer让指定slid值对于的图层可见
    WKT
    消息的分类
    MFC画图
    MFC画文字DrawText,GetTextExtent,GetTextMetrics
    djvu是什么
    代码提示插件 Visual Assistxv
  • 原文地址:https://www.cnblogs.com/shixiemayi/p/9613651.html
Copyright © 2020-2023  润新知