美文网首页
设计模式-Adapter

设计模式-Adapter

作者: ZjyMac | 来源:发表于2018-05-07 13:56 被阅读0次

一,Adapter模式详解

  • 适配器模式定义
    将一个接口转换成客户希望的另一个接口,适配器模式使接口不兼容的那些类一起工作,其别名为包装器(Wrapper)

二,类适配器

  • 类适配器的定义
    把适配器的类的api转化为目标类的api
  • UML结构图解释
    image.png
  • 代码详解
public interface Target {
    void sampleOperation1();
    void sampleOperation2();
}
public class Adaptee {
    public void sampleOperation1(){
        Log.e("zjy","sampleOperation1");
    }
}

public class Adapter extends Adaptee implements Target{
    @Override
    public void sampleOperation2() {
        Log.e("zjy","sampleOperation2");
    }
}

 Adapter adapter=new Adapter();
        adapter.sampleOperation2();
        adapter.sampleOperation1();
  • 总结
    a:类适配器使用对象继承的方式,是静态的定义的方式
    b:对于类适配器,适配器可以重新定义adaptee的部分行为
    c:对于类适配器,仅仅引入一个对象,并不需要额外的引用来间接得到Adaptee
    d:对于类适配器,由于类适配器直接继承了Adaptee,使得适配器不能和Adaptee的子类一起工作

三,对象适配器

  • 对象适配器的定义
    与类适配器一样,对象的适配器模式把适配的类的API转化为目标类的API,与类适配器模式不同的是,对象的适配器不是使用继承关系连接到Apaptee类,而是使用委派关系连接到Adaptee类

  • UML结构图解释

    image.png
  • 代码详解

public class AdapterObject  implements Target{
    private Adaptee adaptee;
    public AdapterObject(Adaptee adaptee){
        this.adaptee=adaptee;
    }
    @Override
    public void sampleOperation1() {
        adaptee.sampleOperation1();
    }

    @Override
    public void sampleOperation2() {
        Log.e("zjy","sampleOperation2");
    }
}
  • 总结
    a:对象适配器使用对象的组合,是动态组合的方式
    b:对于对象适配器,一个适配器可以把多种不同的源适配到同一目标上
    c:对于对象适配器,要重定义adaptee的行为比较困难
    b:对象适配器,需要额外的引用间接得到adaptee

四,Adapter模式在android中的应用

  • ListView
image.png

(1)ListView的布局是是由一条条Item组成,每一个Item又是一个View,通过Adapter适配器这个桥梁将VIew添加到ListView中。
(2)一个Adapter是AdapterView视图与数据的桥梁,adapter提供对数据的访问,也负责为每一个数据产生一个对应的view
(3)每一项数据产生对应的view后,将view添加到Listview中
(4)MVC模式,adapter代表c

相关文章

  • 11.3设计模式-适配器-详解

    设计模式-适配器adapter模式 adapter模式详解 adapter模式在android中的实际运用1.li...

  • 浅谈设计模式之适配器模式

    适配器模式(Adapter Pattern) 概述: 在设计模式中,适配器模式(adapter pattern)有...

  • 设计模式-adapter设计模式

    效果图 1.定义 将一种对象适配成另一种对象 2.示例 3.使用 listview的适配器 4.总结 1.适配器模...

  • Adapter模式(设计模式)

    对象适配器模式(使用委托的适配器) 个人理解 用一个比喻来描述比较好,比如:中国现在用电的标准电压是220V交流电...

  • 设计模式-Adapter

    一,Adapter模式详解 适配器模式定义将一个接口转换成客户希望的另一个接口,适配器模式使接口不兼容的那些类一起...

  • Adapter 设计模式

    adapter 模式详解 类的适配器模式 把适配的类的 API转换为目标类的API。 对象适配器对象的适配器模式 ...

  • 浅谈GoF23设计模式-“Adapter”模式

    “Adapter”模式为结构型设计模式,C#当中主要使用对象适配器。“Adapter”模式定义:将一个类的接口转换...

  • 简说设计模式之适配器模式

    前言:对于设计模式基础概念可以去看[简说设计模式之设计模式概述] 一、什么是适配器模式 适配器模式(Adapter...

  • Typescript 适配器模式(Adapter)

    标签: 前端 设计模式 适配器模式 typescript Adapter 请仔细阅读下面代码,理解其中的设计理念。...

  • 6、结构型模式-适配器设计模式

    1、接口之间的桥梁-适配器设计模式 简介:讲解Adapeter设计模式和应用场景 适配器模式(Adapter Pa...

网友评论

      本文标题:设计模式-Adapter

      本文链接:https://www.haomeiwen.com/subject/uemdcftx.html