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

1、适配器模式概述

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

  将本来不兼容不能在一块儿工做的类添加适配处理类,使其能够在一块儿工做。this

2、适配器模式场景

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

3、适配器模式示例

  (1)定义USB接口code

 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的适配器blog

  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 }

  测试:get

 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 }

  控制台输出:class

我是PS/2接口的键盘!

  b.对象适配器test

 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接口的键盘!
相关文章
相关标签/搜索