设计模式之---适配器模式

in steemit •  7 years ago 

适配器模式是android开发中最常用的模式之一,我们在开发显示列表时经常会用到

定义

适配器模式(Adapter Pattern)
Convert the interface of a class into another interface clientsexpect. Adapter lets classes work together that couldn't other-wise because of incompatible interfaces.
将一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。

优点

  • 通过接口转换可以补偿原来系统因接口设计不兼容遗留的问题

类图 略

主要类

  • 目标类 Target
  • 源类 Adaptee
  • 适配器类 Adapter
    代码
public class Adaptee {
    public void doSomething(){
        System.out.println("Adaptee");
  }
}
public class Adapter extends Adaptee implements Target {
    public void request() {
        super.doSomething();
  }
}
public class ConcreteTarget implements Target {
    public void request() {
        System.out.println("ConcreteTarget");
  }
}
public interface Target {
    public void request();
}

运行结果

ConcreteTarget
Adaptee
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!