適配器模式

在設計模式中，適配器模式（adapter pattern），有時候也稱為包裝器（wrapper），它將一個類的接口轉接成客戶所預期的接口。適配器使得因接口不兼容而不能在一起工作的類能在一起工作，做法是將要被適配的已存在的類實例或接口，包裹在預期的目標接口的實現之中。

## 概述

適配器模式是著名的《設計模式：可復用物件導向軟體的基礎》所收錄的二十三個模式之一。此書描述了如何解決常見的設計問題，以設計出彈性且異重用的物件導向軟體（亦即更容易實現、更改、測試、維護和重用的物件）。

## 結構

在上面的UML類圖中，`client`類要求`target`接口，而不可以直接重複使用`adaptee`類，因為它的接口不符合`target`接口。`client`轉而合作於`adapter`類，它依據`adaptee`而實現了`target`接口：

- 對象適配器`object adapter`實現`target`接口，總是通過在運行時委託給`adaptee`對象（`adaptee.specificOperation()`）。
- 類適配器`class adapter`實現`target`接口，總是通過在編譯時繼承自`adaptee`類（`specificOperation()`）。

### 對象適配器模式

在這種適配器模式中，適配器容納一個它包裹的類的實例。在這種情況下，適配器會調用被包裹對象的實例。

### 類適配器模式

這種適配器模式使用多個多態接口，實現或者繼承它預期的目標接口和事先存在的被適配接口二者。預期的目標接口典型的被創建為純接口類，特別是在不支持類的多重繼承的程式語言比如Java（JDK 1.8以前）之中。

## 示例

在下面的對象適配器模式例子中，模擬使用Micro USB接頭的早期安卓手機充電器，在不更換USB硬體#線纜的前提下，給使用Lightning接頭的早期蘋果手機充電。這裡的交流適配器連帶USB線纜組成的USB充電器是客戶`client`，USB線纜所插入的手機USB接頭是目標接口`target`，而手機使用的與它不適配的接頭是被適配者`adaptee`，為了清晰性可以為適配器採用類名字`[<small>被适配者</small>]To[<small>目标接口</small>]Adapter`，比如這個例子中的適配器`LightningToMicroUsbAdapter`。適配器應當有一個構造子方法，具有一個`adaptee`類變量作為參數。這個參數將被傳遞給適配器的一個實例成員。在調用`clientMethod`的時候，它將訪問到這個`adaptee`，從而允許訪問所需求的`adaptee`的數據，並在這個數據上進行運算而生成想要的輸出。

### Java

下面是Java例子：

```Java
interface ILightningPhone {
    void recharge();
    void useLightning();
}

interface IMicroUsbPhone {
    void recharge();
    void useMicroUsb();
}

class Iphone implements ILightningPhone {
    private boolean connector;

    @Override
    public void useLightning() {
        connector = true;
        System.out.println("Lightning connected");
    }

    @Override
    public void recharge() {
        if (connector) {
            System.out.println("Recharge started");
            System.out.println("Recharge finished");
        } else {
            System.out.println("Connect Lightning first");
        }
    }
}

class Android implements IMicroUsbPhone {
    private boolean connector;

    @Override
    public void useMicroUsb() {
        connector = true;
        System.out.println("MicroUsb connected");
    }

    @Override
    public void recharge() {
        if (connector) {
            System.out.println("Recharge started");
            System.out.println("Recharge finished");
        } else {
            System.out.println("Connect MicroUsb first");
        }
    }
}
/* exposing the target interface while wrapping source object */
class LightningToMicroUsbAdapter implements IMicroUsbPhone {
    private final ILightningPhone lightningPhone;

    public LightningToMicroUsbAdapter(ILightningPhone lightningPhone) {
        this.lightningPhone = lightningPhone;
    }

    @Override
    public void useMicroUsb() {
        System.out.println("MicroUsb connected");
        lightningPhone.useLightning();
    }

    @Override
    public void recharge() {
        lightningPhone.recharge();
    }
}

public class AdapterDemo {
    static void rechargeMicroUsbPhone(IMicroUsbPhone phone) {
        phone.useMicroUsb();
        phone.recharge();
    }

    static void rechargeLightningPhone(ILightningPhone phone) {
        phone.useLightning();
        phone.recharge();
    }

    public static void main(String[] args) {
        Android android = new Android();
        Iphone iPhone = new Iphone();

        System.out.println("Recharging android with MicroUsb");
        rechargeMicroUsbPhone(android);

        System.out.println("Recharging iPhone with Lightning");
        rechargeLightningPhone(iPhone);

        System.out.println("Recharging iPhone with MicroUsb");
        rechargeMicroUsbPhone(new LightningToMicroUsbAdapter (iPhone));
    }
}
```

輸出：

```output
Recharging android with MicroUsb
MicroUsb connected
Recharge started
Recharge finished
Recharging iPhone with Lightning
Lightning connected
Recharge started
Recharge finished
Recharging iPhone with MicroUsb
MicroUsb connected
Lightning connected
Recharge started
Recharge finished
```

### C#

下面是C#例子：

```c#
public interface ILightningPhone {
	void ConnectLightning();
	void Recharge();
}

public interface IUsbPhone {
	void ConnectUsb();
	void Recharge();
}

public sealed class AndroidPhone : IUsbPhone {
	private bool isConnected;

	public void ConnectUsb() {
		this.isConnected = true;
		Console.WriteLine("Android phone connected.");
	}

	public void Recharge() {
		if (this.isConnected) {
			Console.WriteLine("Android phone recharging.");
		}
		else {
			Console.WriteLine("Connect the USB cable first.");
		}
	}
}

public sealed class ApplePhone : ILightningPhone {
	private bool isConnected;

	public void ConnectLightning() {
		this.isConnected = true;
		Console.WriteLine("Apple phone connected.");
	}

	public void Recharge() {
		if (this.isConnected) {
			Console.WriteLine("Apple phone recharging.");
		}
		else {
			Console.WriteLine("Connect the Lightning cable first.");
		}
	}
}

public sealed class LightningToUsbAdapter : IUsbPhone {
	private readonly ILightningPhone lightningPhone;

	private bool isConnected;

	public LightningToUsbAdapter(ILightningPhone lightningPhone) {
		this.lightningPhone = lightningPhone;
	}

	public void ConnectUsb() {
		this.lightningPhone.ConnectLightning();
	}

	public void Recharge() {
		this.lightningPhone.Recharge();
	}
}

public void Main() {
	ILightningPhone applePhone = new ApplePhone();
	IUsbPhone adapterCable = new LightningToUsbAdapter(applePhone);
	adapterCable.ConnectUsb();
	adapterCable.Recharge();
}
```

輸出：

```output
Apple phone connected.
Apple phone recharging.
```

### Python

下面是Python例子：

```python
from abc import ABCMeta, abstractmethod

connected_prompt = "{} connected."
connected_first_prompt = "Connect {} first."
recharge_prompt = ["Recharge started.", "Recharge finished."]

class MicroUsbPhone(metaclass=ABCMeta):
    @abstractmethod
    def recharge(self): pass
    @abstractmethod
    def use_micro_usb(self): pass

class LightningPhone(metaclass=ABCMeta):
    @abstractmethod
    def recharge(self): pass
    @abstractmethod
    def use_lightning(self): pass

class Android(MicroUsbPhone):
    def __init__(self):
        self.connector = "MicroUSB"
        self.connected = False
    def use_micro_usb(self):
        self.connected = True
        print(connected_prompt.format(self.connector))
    def recharge(self):
        if self.connected:
            for state in recharge_prompt:
                print(state)
        else:
            print(connected_first_prompt.format(self.connector))

class IPhone(LightningPhone):
    def __init__(self):
        self.connector = "Lightning"
        self.connected = False
    def use_lightning(self):
        self.connected = True
        print(connected_prompt.format(self.connector))
    def recharge(self):
        if self.connected:
            for state in recharge_prompt:
                print(state)
        else:
            print(connected_first_prompt.format(self.connector))

class LightningToMicroUsbAdapter(MicroUsbPhone):
    def __init__(self, phone):
        assert isinstance(phone, LightningPhone)
        self.connector = "MicroUSB"
        self.connected = False
        self.adaptee = phone
    def use_micro_usb(self):
        self.connected = True
        print(connected_prompt.format(self.connector))
        self.adaptee.use_lightning()
    def recharge(self):
        if self.connected:
            self.adaptee.recharge()
        else:
            print(connected_first_prompt.format(self.connector))

def micro_usb_recharger(phone):
    assert isinstance(phone, MicroUsbPhone)
    phone.use_micro_usb()
    phone.recharge()

def lightning_recharger(phone):
    assert isinstance(phone, LightningPhone)
    phone.use_lightning()
    phone.recharge()

def demo():
    android = Android()
    iphone = IPhone()
    print("Recharging Android with MicroUSB recharger.")
    micro_usb_recharger(android)
    print()
    print("Recharging iPhone with Lightning recharger.")
    lightning_recharger(iphone)
    print()
    print("Recharging iPhone with MicroUSB recharger.")
    micro_usb_recharger(LightningToMicroUsbAdapter(iphone))
```

其執行：

```pycon
>>> demo()
Recharging Android with MicroUSB recharger.
MicroUSB connected.
Recharge started.
Recharge finished.

Recharging iPhone with Lightning recharger.
Lightning connected.
Recharge started.
Recharge finished.

Recharging iPhone with MicroUSB recharger.
MicroUSB connected.
Lightning connected.
Recharge started.
Recharge finished.
```