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

    使用场景: 接口转换

    一、对象适配器优先选用

    优选的原因:多用聚合,少用继承

    原始接口类:

    public class Adaptee {

    public void standardRequest(){

    System.out.println("这是原始标准接口!");

    }
    }

    目标接口:

    public interface Target {

    public void newRequest();

    }

    适配器类:

    //聚合的方式,适配器类中“原始接口对象”作为其成员对象
    public class Adapter implements Target {

    public Adapter(Adaptee apt){
    this.apt=apt;
    }

    //实现新接口中的方法
    public void newRequest() {
    System.out.println("调用老接口之前进行一些预处理");
    this.apt.standardRequest();//开始调用老接口

    }

    private Adaptee apt=null;

    }

    测试:

    public class Main {

    public static void main(String[] args) {
    System.out.println("测试对象适配器。。。");

    //创建“原始接口类对象”和“适配器对象”
    Adaptee theAdaptee=new Adaptee();
    Target theTarget=new Adapter(theAdaptee);

    //调用新接口
    theTarget.newRequest();
    }

    }

    运行结果:

    二、类适配器

    原始接口类:

    public class Adaptee {

    public void standardRequest(){

    System.out.println("这是原始标准接口!");

    }
    }

    目标接口:

    public interface Target {

    public void newRequest();

    }

    适配器类:

    //继承的方式,“原始接口类”中的方法通过继承得到,并在新接口的方法中被调用
    public class Adapter extends Adaptee implements Target {

    //实现新接口中的方法
    public void newRequest() {
    System.out.println("调用老接口之前进行一些预处理");
    super.standardRequest();
    }

    }

    测试:

    public class Main {

    public static void main(String[] args) {
    System.out.println("测试类适配器");

    //创建适配器对象
    Target theTarget=new Adapter();

    //调用新接口
    theTarget.newRequest();

    }

    }

    运行结果:



  • 相关阅读:
    WeChat小程序开发(五、前端总结)
    前端实现复制到剪贴板
    vue的自定义指令含大写字母会失效
    如何把网页变成黑白
    原生JS offsetX和offsetY引起抖动
    jQuery中prop方法和attr方法区别
    Js for循环中的闭包 & let和var的混用对比
    html和body标签默认高度为0带来的影响
    JS字符串数组降维
    CSS浮动流脱标的字围现象
  • 原文地址:https://www.cnblogs.com/edisonfeng/p/2294115.html
Copyright © 2011-2022 走看看