• 适配器模式


    本文章,摘抄自:2018黑马程序最新面试题汇总

    适配器模式将某个类的接口转换成客户端期望的另一个接口表示,目的是消除由于接口不匹配所造成的类的兼容性问题。
    主要分为三类:

    类的适配器模式、对象的适配器模式、接口的适配器模式。

    类的适配器模式:

    1 public class Source {
    2     public void methodSource() {
    3         System.out.println("this is original methodSource!");
    4     }
    5 }
    1 public interface ITargetable {
    2 
    3     /* 与原类中的方法相同 */
    4     public void methodSource();
    5 
    6     // 新类的方法
    7     public void methodAdapter();
    8 }
    1 public class Adapter extends Source implements ITargetable {
    2 
    3     @Override
    4     public void methodAdapter() {
    5         System.out.println("this is the targetable methodAdapter!");
    6     }
    7 
    8 }

    测试方法:

    1 @Test
    2     public void testClasses() {
    3         ITargetable targetable = new Adapter();
    4         targetable.methodSource();
    5         targetable.methodAdapter();
    6     }

    对象的适配器模式:基本思路和类的适配器模式相同,只是将 Adapter 类作修改,这次不继承 Source 类,而是持有 Source 类的实例,以达到解决兼容性的问题。

     1 import cn.silence.face.designmode.adapter.classes.ITargetable;
     2 import cn.silence.face.designmode.adapter.classes.Source;
     3 
     4 public class Wrapper implements ITargetable {
     5 
     6     private Source source;
     7 
     8     public Wrapper(Source source) {
     9         super();
    10         this.source = source;
    11     }
    12 
    13     @Override
    14     public void methodSource() {
    15         source.methodSource();
    16     }
    17 
    18     @Override
    19     public void methodAdapter() {
    20         System.out.println("this is the targetable method!");
    21 
    22     }
    23 
    24 }

    测试方法:

    1 @Test
    2     public void testObects() {
    3         Source source = new Source();
    4         ITargetable targetable = new Wrapper(source);
    5         targetable.methodSource();
    6         targetable.methodAdapter();
    7     }

    接口的适配器模式:     

    接口的适配器是这样的:有时我们写的一个接口中有多个抽象方法,当我们写该接口的实现类时,必须实现该接口的所有方法,这明显有时比较浪费,因为并不是所有的方法都是我们需要的,

    有时只需要某一些,此处为了解决这个问题,我们引入了接口的适配器模式,借助于一个抽象类,该抽象类实现了该接口,实现了所有的方法,而我们不和原始的接口打交道,只和该抽象类取得联系,所以我们写一个类,

    继承该抽象类,重写我们需要的方法就行。

  • 相关阅读:
    DotNetty网络通信框架学习之初识Netty
    DotNetty网络通信框架学习
    DotNetty网络通信框架学习之源码分析
    MODBUS协议解析中常用的转换帮助类(C#)
    C# 键盘钩子
    C# 实现http不同方法的请求
    C# 中List<T>与DataSet之间的转换
    C# 将文件夹中文件复制到另一个文件夹
    WinForm中 Asp.Net Signalr消息推送测试实例
    redis安装教程
  • 原文地址:https://www.cnblogs.com/ffeiyang/p/9542674.html
Copyright © 2020-2023  润新知