GoLang设计模式20 - 适配器模式(结构型)
说明
适配器模式是一种结构型设计模式。我们用常用的两种笔记本电脑来说明一下这种设计模式。
我们常用的笔记本无非是这两大类:
- Macbook Pro
- Windows Laptop
当前这两类笔记本常见的一个区别大概是USB接口的类型了:
- Macbook Pro的USB接口现在多为扁圆形的Type-C接口
- Windows笔记本的USB接口则多为方形的Type-A接口
现在我手上有一个Type-C扁圆口的U盘,但是我用的笔记本Windows,这该怎么办呢?
这也是编程时常遇到的一种问题:
我们有一个已经封装严谨的类(如Windows笔记本),它提供了一些功能并指定对接参数的类型(如Type-A方形USB接口)。但是现在有一个不同类型的实例(Type-C扁圆形口U盘),也想用这个已经封装好的类提供的功能。此时该怎么做?
这时就可以应用适配器模式了。我们创建一个Adapter类,他可以提供如下功能:
- 按照已有类指定的参数类型进行实现
- 转译调用方的请求
在我们前面的例子中,这个Adapter就可以是一个转接器,它接收Type-C扁圆形接口的输入,提供Type-A方形接口的数据输出,从而能让我们顺利地使用上手头的方口U盘。
UML类图
看下类图:

然后是前面举的例子的类图:

代码
示例代码如下:
client.go
1 package main 2 3 type client struct { 4 } 5 6 func (c *client) insertSquareUsbInComputer(com computer) { 7 com.insertInSquarePort() 8 }
main.go
1 func main() { 2 3 client := &client{} 4 mac := &mac{} 5 client.insertSquareUsbInComputer(mac) 6 windowsMachine := &windows{} 7 windowsMachineAdapter := &windowsAdapter{ 8 windowMachine: windowsMachine, 9 } 10 client.insertSquareUsbInComputer(windowsMachineAdapter) 11 12 }
1 type computer interface { 2 insertInSquarePort() 3 } 4 5 type mac struct { 6 } 7 8 func (m *mac) insertInSquarePort() { 9 fmt.Println("Insert square port into mac machine") 10 } 11 12 type windows struct{} 13 14 func (w *windows) insertInCirclePort() { 15 fmt.Println("Insert circle port into windows machine") 16 } 17 18 type windowsAdapter struct { 19 windowMachine *windows 20 } 21 22 func (w *windowsAdapter) insertInSquarePort() { 23 w.windowMachine.insertInCirclePort() 24 }
输出内容:
1 Insert square port into mac machine 2 Insert circle port into windows machine
浙公网安备 33010602011771号