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

    本文章,摘抄自: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     }

    接口的适配器模式:     

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

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

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

  • 相关阅读:
    sqlserver优化查询
    DateADD日期Sql
    sql 数据字段类型
    sql Server 发送邮件 错误类型及原因
    EassyUI内置方法与属性
    这货不是 for循环
    1.switch选择结构 3.多重if选择结构和switch比对 4.总结选择结构 5.使用hasNextInt()解决用户从控制台输入为非整型问题
    1.基本选择结构if 2.逻辑运算符 3.if-else 4.多重if选择结构 5.嵌套if选择结构
    编写java程序步骤
    css3
  • 原文地址:https://www.cnblogs.com/ffeiyang/p/9542674.html
Copyright © 2011-2022 走看看