GOF23设计模式之适配器模式(Adapter)

一、适配器模式概述

  将一个类的接口转换成客户可用的另外一个接口。

  将原本不兼容不能在一起工作的类添加适配处理类,使其可以在一起工作。

二、适配器模式场景

  要想只有USB接口的电脑想使用PS/2接口的键盘,必须使用PS/2转USB的适配器。

三、适配器模式示例

  (1)定义USB接口

 1 /**
 2  * 客户所期待的接口(相当于USB接口)
 3  * @author CL
 4  *
 5  */
 6 public interface Target {
 7     
 8     void handleReq();
 9 
10 }

  (2)定义PS/2键盘

 1 /**
 2  * 被适配的类 (相当于例子中的PS/2键盘)
 3  * @author CL
 4  *
 5  */
 6 public class Adaptee {
 7     
 8     public void request() {
 9         System.out.println("我是PS/2接口的键盘!");
10     }
11 
12 }

  (3)定义PS/2转USB的适配器

  a. 类适配器

 1 /**
 2  * 适配器(相当于可以将PS/2接口转换成USB接口的适配器本身)
 3  *     类适配器方式
 4  * @author CL
 5  *
 6  */
 7 public class Adapter extends Adaptee implements Target {
 8 
 9     public void handleReq() {
10         super.request();
11     }
12 
13 }

  测试:

 1 /**
 2  * 客户端类(相当于只能识别USB接口键盘的电脑)
 3  * @author CL
 4  *
 5  */
 6 public class Client {
 7     
 8     public void test(Target t) {
 9         t.handleReq();
10     }
11     
12     public static void main(String[] args) {
13         Client c = new Client();
14         Adaptee a = new Adaptee();
15         
16         Target t = new Adapter();    //类适配器方式
17         
18         c.test(t);
19     }
20 
21 }

  控制台输出:

我是PS/2接口的键盘!

  b.对象适配器

 1 /**
 2  * 适配器(相当于可以将PS/2接口转换成USB接口的适配器本身)
 3  *         对象适配器方式,使用了组合的方式跟被适配对象整合
 4  * @author CL
 5  *
 6  */
 7 public class Adapter implements Target {
 8     
 9     private Adaptee adaptee;
10     
11     public Adapter(Adaptee adaptee) {
12         this.adaptee = adaptee;
13     }
14 
15     public void handleReq() {
16         adaptee.request();
17     }
18 
19 }

  测试:

 1 /**
 2  * 客户端类(相当于只能识别USB接口键盘的电脑)
 3  * @author CL
 4  *
 5  */
 6 public class Client {
 7     
 8     public void test(Target t) {
 9         t.handleReq();
10     }
11     
12     public static void main(String[] args) {
13         Client c = new Client();
14         Adaptee a = new Adaptee();
15         
16         Target t = new Adapter3();    //类适配器方式
17         
18         c.test(t);
19     }
20 
21 }

  控制台输出:

我是PS/2接口的键盘!

 

posted @ 2018-01-16 17:50  C3Stones  阅读(339)  评论(0编辑  收藏  举报