设计模式-接口型模式-适配器模式

适配器模式

把一个类的接口转换成客户端所期待的另外一种接口,从而使原接口不匹配而没法在一块儿工做的两个类能在一块儿工做this

功能相似可是接口不一样这时就能够使用适配器,通常状况下在前期第一时间考虑经过重构统一接口。好比在使用第三方开发组件的时候,本身的系统接口与组件接口不一样,不用为了迎合去改本身的接口能够使用适配器模式。code

Target类目标接口客户端可识别,Adaptee须要适配的类,Adapter适配器类orm

//类适配器
class Adaptee{
  public void sepcialMethod(){
    System.out.println("yyx!");
  }
}
interface Target(){
  public void normalMethod();
}
class actualTarget implements Target(){
  public void normalMethod(){
    System.out.println("yyx");
  }
}
class Adapter extends Adaptee implements Target(){
  public void normalMethod(){
    super.sepcialMethod();
  }
}
//对象适配器
class Adapter implements Target(){
  private Adaptee adaptee;
  public Adapter(Adaptee adaptee){
    this.adaptee = adaptee;
  }
  poublic void normalMethod(){
    this.adaptee.sepecialMethod();
  }
}

JAVAIO中有许多用到了对象适配器对象

InputSreamReader是适配器类 StreamDecoder(传入InputStream,这个类将InputStream从字节流变成了字符流)是适配者 Reader是目标类 将InputStream和Reader适配。接口

StringReader是适配器类 String是适配者 Reader是目标类 将String和Reader适配。ci

相关文章
相关标签/搜索