适配器模式的定义与使用介绍

零下一度
零下一度 原创
2017-07-18 09:51:15 1183浏览

适配器模式的定义

  适配器模式:将一个类的接口转换成客户希望的另一个接口。适配器模式让那些接口不兼容的类可以一起工作

Adapter Pattern:Convert the interface of a class into another interface clients expect.Adapter lets classes work together that couldn't otherwise because of incompatible interface.

  适配器模式的别名为包装器(Wrapper)模式,它既可以作为类结构型模式,也可以作为对象结构型模式。在适配器模式定义中所提及的接口是指广义的接口,它可以表示一个方法或者方法的集合。

已经存在的子类,适配的对象
public class Adaptee {public void adapteeMethod(){
        System.out.println("适配方法");
    }
}
适配器接口
public interface Target {/** * 适配的接口     */void adapteeMethod();/** * 新增接口     */void adapterMethod();
}
接口实现
public class Adapter implements Target{private Adaptee adaptee;public Adapter(Adaptee adaptee) {this.adaptee = adaptee;
    }
    @Overridepublic void adapteeMethod() {this.adaptee.adapteeMethod();
    }

    @Overridepublic void adapterMethod() {
        System.out.println("新增接口");
    }
}
测试
public static void main(String[] args) {
    Target target = new Adapter(new Adaptee());
    target.adapteeMethod();
    target.adapterMethod();
}

配器模式包含一下三个角色:

  1:Target(目标抽象类):目标抽象类定义客户所需的接口,可以是一个抽象类或接口,也可以是具体类。在类适配器中,由于C#语言不支持多重继承,所以它只能是接口。

  2:Adapter(适配器类):它可以调用另一个接口,作为一个转换器,对Adaptee和Target进行适配。它是适配器模式的核心。

  3:Adaptee(适配者类):适配者即被适配的角色,它定义了一个已经存在的接口,这个接口需要适配,适配者类包好了客户希望的业务方法。


以上就是适配器模式的定义与使用介绍的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。