[06]Go设计模式:适配器模式(Adapter Pattern)

适配器模式

一、简介

适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。这种模式涉及到一个单一的类,该类负责加入独立的或不兼容的接口功能。例如: 在现实生活中,我们的笔记本电脑的工作电压大多数都是20V,而我国的家庭用电是220V,如何让20V的笔记本电脑能够工作在220V的电压下工作?答案:引入一个电源适配器,俗称变压器,有了这个电源适配器,生活用电和笔记本电脑即可兼容。

二、代码

package main

import "fmt"

// 将一个类的接口转换成客户希望的另一个接口,Adapter模式使得原本由于接口
// 不兼容而不能一起工作的那些类可以一起工作

// 定义一个新的接口
type Target interface {
    Process()
}

// 定义一个老的接口
type Adaptee interface {
    Foo()
    Bar()
}

// 定一个Adapter接口
type Adapter struct {
    adaptee Adaptee
}

func (a *Adapter) Process(){
    fmt.Println("在Adapter中执行process()")
    a.adaptee.Bar()
    a.adaptee.Foo()
}

// 实现旧接口struct
type oldAdaptee struct {

}

func (o *oldAdaptee) Foo(){
    fmt.Println("在旧接口中执行foo()")
}

func (o *oldAdaptee) Bar(){
    fmt.Println("在旧的接口中执行bar()")
}

func main(){
    oa := new(oldAdaptee)
    // 定一个适配器对象
    adapter := new(Adapter)
    adapter.adaptee = oa
    adapter.Process()
}

完整代码地址: https://gitee.com/ncuzhangben/GoStudy/tree/master/go-design-pattern/06-Adapter

三、参考资料

1、 https://www.runoob.com/design-pattern/adapter-pattern.html

2、 https://blog.csdn.net/cloudUncle/article/details/83448727

猜你喜欢

转载自www.cnblogs.com/0pandas0/p/12045236.html