zoukankan      html  css  js  c++  java
  • 适配器模式

    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、适配器的作用

    • 将目标类和适配者类解耦,通过引入一个适配器类重用现有的是配者类,而无需修改原有代码
    • 通过适配器,客户端可以调用同一接口,因而对客户端来说是透明的
  • 相关阅读:
    C#中Dictionary的用法
    System.Timers.Timer用法
    C#中的异步调用及异步设计模式(三)——基于事件的异步模式
    C#中的异步调用及异步设计模式(二)——基于 IAsyncResult 的异步设计模式
    C#中的异步调用及异步设计模式(一)
    [你必须知道的异步编程]——异步编程模型(APM)
    strncasecmp与strcasecmp用法
    C语言之strrchr函数
    HDU 5289 Assignment (ST算法区间最值+二分)
    poj 1733 Parity game(种类并查集)
  • 原文地址:https://www.cnblogs.com/fenghh/p/9618086.html
Copyright © 2011-2022 走看看