[06] Go Design Patterns: Adapter mode (Adapter Pattern)

Adapter mode

I. Introduction

Adapter mode (Adapter Pattern) is used as a bridge between two of incompatible interfaces. This type of design pattern belongs structural model, which combines the functionality of two separate interfaces. This model involves a single class that is responsible for adding separate or incompatible interface functions. For example: In real life, our most laptop operating voltage is 20V, while China's household electricity is 220V, 20V how to make the laptop work can work at a voltage of 220V? The answer: the introduction of a power adapter, commonly known as transformers, can be compatible with this power adapter, electricity consumption and laptops.

Second, the code

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()
}

The complete code Address: https://gitee.com/ncuzhangben/GoStudy/tree/master/go-design-pattern/06-Adapter

Third, reference materials

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

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

Guess you like

Origin www.cnblogs.com/0pandas0/p/12045236.html