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

    适配器(Adapter)模式概述

      将一个类的接口转换成客户方期望的接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。

    模式中的角色

      1 目标接口(Target):客户方所期待的接口。目标可以是具体的或抽象的类,也可以是接口。

      2 需要适配的类(Adaptee):需要适配的类或适配者类。

      3 适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口。  

     模式图:

    例子:

    //客户方期待的接口 ,目标接口
    public interface Target {
    
        //期待的方法
        void targetMethod1();
    
        void targetMethod2();
    
    }
    
    
    
    //需要适配的类
    public class Adaptee {
        
        public void localMethod1(){
            System.out.println("需要适配的类中的方法1");
        }
    
        public void localMethod2(){
            System.out.println("需要适配的类中的方法2");
        }
    
    }
    
    
    
    //适配器
    //通过包装将一个类的接口转换成客户希望的另外一个接口。 
    public class Adapter implements Target{
        
        //需要被适配的类
        private Adaptee adaptee = new Adaptee();
        
        public Adapter(){}
        
        /**
         * 将需要适配的类中的方法转为客户端需要的方法
         */
        @Override
        public void targetMethod1() {
            this.adaptee.localMethod1();
        }
    
        @Override
        public void targetMethod2() {
            this.adaptee.localMethod2();
        }
    
    }
    
    
    
    
    
    public class Client{
    
        //客户端调用
        public static void main(String[] args){
    
            // 客户端通过Target来调用
            Target target = new Adapter();
            target.targetMethod1();
            target.targetMethod2();
        }
    
    }

    适配器适用场景

        5.3.1 系统需要使用现有的类,而这些类的接口不符合系统的接口。

        5.3.2 想要建立一个可以重用的类,用于与一些彼此之间没有太大关联的一些类,包括一些可能在将来引进的类一起工作。

        5.3.3 两个类所做的事情相同或相似,但是具有不同接口的时候。

        5.3.4 旧的系统开发的类已经实现了一些功能,但是客户端却只能以另外接口的形式访问,但我们不希望手动更改原有类的时候。

        5.3.5 使用第三方组件,组件接口定义和自己定义的不同,不希望修改自己的接口,但是要使用第三方组件接口的功能。

    适配器应用

      DataAdapter,用于DataSet和数据源之间的适配器

    end

  • 相关阅读:
    ElasticSearch集群设置
    NEST与JSON语法对照 一 match与multi_match
    某墙尼妹,用个Response.Filter来解决StackExchange.Exceptional中google cdn的问题
    高频
    Linux 后台执行命令
    Mysql 常用函数汇总
    Golang 昨天、今天和明天
    Golang——Cron 定时任务
    Golang 资料整理
    Golang: for range
  • 原文地址:https://www.cnblogs.com/luangeng/p/6052799.html
Copyright © 2011-2022 走看看