美文网首页
设计模式-适配器(adapter)模式

设计模式-适配器(adapter)模式

作者: qyfl | 来源:发表于2019-10-07 21:48 被阅读0次

主要角色

  • 适配器

职责

面对已存在的类,它的方法不满足部分用户的需求的时候,需要做一层转换。

角色关系

  • 对象
  • 被适配
  • 适配器,就是做转换的动作。

类图

类关系示意图

代码

public class Adaptee {
    public void adapteeRequest(){
        System.out.println("被适配者的方法");
    }
}
---
public class Adapter extends Adaptee implements Target{
    @Override
    public void request() {
        //...
        super.adapteeRequest();
        //...
    }
}
---
public class ConcreteTarget implements Target {
    @Override
    public void request() {
        System.out.println("concreteTarget目标方法");
    }
}
---
public interface Target {
    void request();
}

使用

public class Test {
    public static void main(String[] args) {
        Target target = new ConcreteTarget();
        target.request();

        Target adapterTarget = new Adapter();
        adapterTarget.request();
    }
}

技巧

  • 对象接口原实现,就是原来的代码实现,这块是不动原代码的。
  • 适配器就做了转换的方法。
  • 适配器模式一个很明显的特征,就是是适配器类既继承,也有实现。

相关文章

网友评论

      本文标题:设计模式-适配器(adapter)模式

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