zoukankan      html  css  js  c++  java
  • 设计模式之GOF23适配器模式

    结构型模式

    核心作用:是从程序的结构上实现松耦合,从而可以扩大整体的 类结构,用来解决更大的问题

    适配器模式adapter

    实际生活中的例子:转换器

    适配器的两种方式:

    1,类适配器(继承)

    /**需要适配的对象
     * @author 小帆敲代码
     *
     */
    public class Adaptee {
      public void request() {
       System.out.println("can do something");
      }
    }

    /**
     *适配器(类适配器)
     * @author 小帆敲代码
     *
     */
    public class Adapter extends Adaptee implements Target {
     @Override
     public void handleReq() {
       super.request();
     }
    }
    /**
     * 客户端
     * @author 小帆敲代码
     *
     */
    public class Client {
      public void test(Target t) {
       t.handleReq();
      }
      public static void main(String[] args) {
       Client c=new Client();
       Target t=new Adapter();
       c.test(t);
      }
    }
    public interface Target {
      public void handleReq();
    }
    2,对象适配器(组合)
    /**需要适配的对象
     * @author 小帆敲代码
     *
     */
    public class Adaptee {
      public void request() {
       System.out.println("can do something");
      }
    }
    /**
     *适配器(对象适配器)
     * @author 小帆敲代码
     *
     */
    public class Adapter2 extends Adaptee implements Target {
     private Adaptee a;
     @Override
     public void handleReq() {
       a.request();
     }
     public Adapter2() {
      
     }
     public Adapter2(Adaptee a) {
      this.a=a;
     }
    }
    public class Client2 {
     public void test(Target t) {
      t.handleReq();
     }
     public static void main(String[] args) {
      Client c=new Client();
      Adaptee a=new Adaptee();
      Target t=new Adapter2(a);
      c.test(t);
     }
    }
    public interface Target {
      public void handleReq();
    }
  • 相关阅读:
    [JavaScript]继续学习DOM事件模型
    [面试]作答整理一些面试题
    [JavaScript]使用jQuery实现无缝轮播
    [JavaScript]使用CSS + jQuery 实现自动轮播图
    [JavaScript]从DOM到jQuery(2)
    [JavaScript]从DOM到jQuery(1)
    [JavaScript]JavaScript中的函数(2)
    [JavaScript]JavaScript中的函数(1)
    [JavaScript]JavaScript中的Array
    React练习 7 :点击div,显示innerHTML
  • 原文地址:https://www.cnblogs.com/code-fun/p/11330513.html
Copyright © 2011-2022 走看看