适配器模式

xiaoxiao2021-02-28  24

适配器模式

什么是适配器模式?

将一个接口转换成客户希望的另一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。

模式中的角色:

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

     需要适配的类(Adaaptee):需要适配的类或者适配者类。

     适配器(Adapter):通过包装一个需要适配的对象,把接口转换成目标接口。

继承式适配器

//被适配的类(usb)

publicclass Adpatee {

   publicvoid out(){

      System.out.println("可以完成功能!");

   }

}

 

publicinterface Target {

    publicvoid handleRep();

}

 

//适配器本身(相当于转接器)

publicclass  Adpater extends Adpatee implements Target{

   @Override

   publicvoid handleRep() {

      super.out();

   }

}

 

//客户端笔记本(只有USB接口)

publicclass Main {

   publicvoid test1(Target t) {

      t.handleRep();

   }

   publicstaticvoid main(String[] args) {

      Main m = new Main();

      Adpatee ad = new Adpatee();

      Target t = new Adpater();

      m.test1(t);

   }

}

聚合式适配器

//适配器本身(相当于转接器)

publicclass  Adpater implements Target{

   private Adpatee ad;

   @Override

   publicvoid handleRep() {

      ad.out();

   }

   public Adpater(Adpatee ad){

      this.ad = ad;

   }

}

 

//客户端笔记本(只有USB接口)

publicclass Main {

   publicvoid test1(Target t) {

      t.handleRep();

   }

   publicstaticvoid main(String[] args) {

      Main m = new Main();

      Adpatee ad = new Adpatee();

      Target t = new Adpater(ad);

      m.test1(t);

   }

}

 

 

应用:

    经常用做旧系统改造和升级

    如果我们的系统开发之后在也不需要维护,那么很多模式都是没有必要的,但是不幸的是,事实上开发一个系统的代价往往是开发一个系统的数倍。

学习中的场景:

Java.io.InputStreamReader(InputStream)

Java.io.OutputStreamReader(OutputStream)

转载请注明原文地址: https://www.6miu.com/read-2632394.html

最新回复(0)