美文网首页java设计模式笔记
设计模式八--适配器模式

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

作者: 朽木亦自雕 | 来源:发表于2018-10-15 15:34 被阅读20次

    定义

    将一个类的接口转换成客户希望的另外一个接口,从而使两个原本因为不匹配而无法在一起工作的两个类能够在一起工作

    适配器模式中的角色

    1:目标(Target)角色:这就是所期待得到的接口。

    public interface Target
    {
        public void request();
    }
    

    (2)源(Adaptee)角色:现在需要适配的接口。

    public class Adaptee
    {
      public void specificRequest(){}
    }
    

    (3)适配器(Adapter)角色:适配器类是本模式的核心。适配器把源接口转换成目标接口。

    public class Adapter extends Adaptee implements Target
    {
      public void request(){
          super.specificRequest();
      }
    }
    

    调用示例

    public void Client
    {
      public static void main(String [] args)
      {
        Target target = new Adapter();
        target.request();
      }
    }
    

    优点

    增加了类的透明性
    提高了类的复用性
    增强代码的灵活性

    使用场景

    修改一个已经投产中的系统时,对系统中不符合系统接口的类,转换成符合系统接口的类

    参考资料:设计模式(java)

    相关文章

      网友评论

        本文标题:设计模式八--适配器模式

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