设计模式--适配器(Adapter)模式

1.概述

当我们创建好接口后,由于客户的需求改变,我们要把原来的接口改成客户所要求的目标接口,这样就需要修改原来接口中的大量代码。为了解决这一问题,我们可以依靠一个中间介质将原接口和目标接口连接起来,这样原接口和目标接口的相关性就会降低,到时候只要修改中间介质的代码,就能达到客户的需求,所以这里我们用到了适配器模式

2.适配器的实现方式:

(1)通过继承方式

(2)通过委让方式

3.下面我们将对以上两种实现方式进行讲解,我们以电脑充电为例子。

假设:电脑充电只需18v,而电源电压220v;如果我们直接让电脑接入电源,那么电脑就会被烧坏。因此,我们需要一个介质对电源进行降压。

继承方式:

 1 package com.msit.xxx;
 2 
 3 /**
 4  * 电源类:220v;
 5  * 
 6  * @author admin
 7  * 
 8  */
 9 public class Current {
10     public void use220v() {
11         System.out.println("使用220v电压!");
12     }
13 }
 1 package com.msit.xxx;
 2 
 3 /**
 4  * 第一种适配器:继承类型。此时,适配器用的是220v,降压后就为18v
 5  * 
 6  * @author admin
 7  * 
 8  */
 9 public class Adapter1 extends Current {
10     public void use18v() {
11         System.out.println("使用适配器降压!");
12         this.use220v();
13     }
14 }
    public class Computer{
    public static void main(String[] args) {
        // 1.直接使用220v进行充电,结果烧坏电脑
        Current current = new Current();
        current.use220v();
        // 2.使用适配器进行降压,但适配器里面用的还是220v,降压后就是18v。继承方式
        Adapter1 adapter1 = new Adapter1();
        adapter1.use18v();
    }
}    

委让方式:

 1 package com.msit.xxx;
 2 
 3 /**
 4  * 第二种适配器:通过委让实现。不需要继承,只要调用目标接口的实例就行
 5  * 
 6  * @author admin
 7  * 
 8  */
 9 public class Adapter2 {
10     private Current current;
11 
12     public Adapter2(Current current) {
13         this.current = current;
14     }
15 
16     public void use18v() {
17         System.out.println("使用适配器!");
18         this.current.use220v();
19     }
20 }
1 public class Computer{
2     public static void main(String[] args) {
3             // 3.使用委让 实现
4         Adapter2 adapter2 = new Adapter2(new Current());
5         adapter2.use18v();
6     }
7 }    

适配器的优点:

1.将原接口和目标接口进行解耦,减小了它们之间的相关性。

2.不用修改原接口的大量代码,只需要更改适配器的实现体,修改的代码量就少。

原文地址:https://www.cnblogs.com/lirenzhujiu/p/5748176.html