适配器模式

适配器模式

适配器模式(别名:包装器):将一个类的接口转换成客户希望的另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

适配器模式的结构中包括3种角色:

  1.目标(Target):目标是客户所期待(使用)的接口。目标可以是具体的或抽象的类,也可以是接口。

  2.被适配者(Adaptee):被适配者是一个已经存在的类或接口(或抽象类),这个类或接口(或抽象类)需要适配。

  3.适配器(Adapter):适配器是一个类,该类实现了目标接口并包含被适配者的引用,通过包装一个Adaptee对象,把原接口转换成目标接口。

  适配器模式有两种:

  一种是对象适配器模式

  另一种是类适配器模式

对象适配器模式的UML类图如下所示

  适配器模式

  Target代码:

interface Target //客户想使用的接口

{

public abstract void Request();

}

 

  Adaptee代码:

interface Adaptee //需要被适配的接口

{

  public abstract void SpecificRequest();

}

  Adapter代码:

class Adapter implements Target //适配器,将原接口转换成了目标接口

{

    private Adaptee adaptee;//声明Adaptee的引用

    public Adapter(Adaptee adaptee){

        this.adaptee=adaptee;

    }

    public void Request(){

     //这样就可以把表面上调用Request()方法变成实际上调用SpecificRequest()

    adaptee.SpecificRequest();

}

  客户端代码:

class Client

{

    public static void main(String args[]){

        Target target=new Adapter();

        target.Request();//对客户来说,调用的就是Target接口的Request()方法

    }

}

 类适配器模式的UML类图如下所示

适配器模式

  代码如下:

//目标

interface Target

{

public abstract void Request();

}

//被适配者

class Adaptee

{

  public void SpecificRequest(){

  }

}

//适配器

class Adapter extends Adaptee implements Target

{

    public void Request(){

     //这样就可以把表面上调用Request()方法变成实际上调用SpecificRequest()

    super.SpecificRequest();

}

//客户端

class Client

{

    public static void main(String args[]){

        Target target=new Adapter();

        target.Request();//对客户来说,调用的就是Target接口的Request()方法

    }

}

  适配器模式的优点:

  1.目标(Target)和被适配者(Adaptee)是完全解耦的关系,符合“高内聚,低耦合”。

  2.适配器模式满足“开-闭原则”。当添加一个实现Adaptee接口的新类时,不必修改Adapter,Adapter就能对这个新类的实例进行适配。

  适配器模式的应用场景:

  一个程序想使用已经存在的类,但该类所实现的接口和当前程序所使用的接口不一致。

  

 

你可能感兴趣的:(适配器模式)