golang 适配器模式 简单示例记录

19次阅读
没有评论

共计 1089 个字符,预计需要花费 3 分钟才能阅读完成。

package main

import (
    "fmt"
)

// Target 是客户端期望的接口
type Target interface {
    Request() string
}

// Adaptee1 是第一个需要适配的类
type Adaptee1 struct{}

func (a *Adaptee1) SpecificRequest1() string {
    return "Called SpecificRequest1()"
}

// Adapter1 是第一个适配器类
type Adapter1 struct {
    adaptee *Adaptee1
}

func (adapter *Adapter1) Request() string {
    return adapter.adaptee.SpecificRequest1()
}

// Adaptee2 是第二个需要适配的类
type Adaptee2 struct{}

func (a *Adaptee2) SpecificRequest2() string {
    return "Called SpecificRequest2()"
}

// Adapter2 是第二个适配器类
type Adapter2 struct {
    adaptee *Adaptee2
}

func (adapter *Adapter2) Request() string {
    return adapter.adaptee.SpecificRequest2()
}

// AdapterFactory 是适配器工厂
type AdapterFactory struct{}

// GetAdapter 根据条件返回不同的适配器
func (factory *AdapterFactory) GetAdapter(adapterType string) Target {
    switch adapterType {
    case "adapter1":
        return &Adapter1{&Adaptee1{}}
    case "adapter2":
        return &Adapter2{&Adaptee2{}}
    default:
        return nil
    }
}

func main() {
    factory := &AdapterFactory{}
    // 使用第一个适配器
    adapter1 := factory.GetAdapter("adapter1")
    fmt.Println(adapter1.Request()) // 输出: Called SpecificRequest1()

    // 切换到第二个适配器
    adapter2 := factory.GetAdapter("adapter2")
    fmt.Println(adapter2.Request()) // 输出: Called SpecificRequest2()
}
正文完
 0
Eric chan
版权声明:本站原创文章,由 Eric chan 于2024-08-27发表,共计1089字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。