Golang设计模式之适配器模式

Jackey Golang 1,837 次浏览 , , 没有评论
package main

import "fmt"

// 适配器目标接口
type Target interface {
    Request(int, int) string
}

type Adapter struct {
    Adaptee
}

func NewAdapter(adaptee Adaptee) Target {
    return &Adapter{adaptee}
}

// 接口包装
func (ad *Adapter) Request(a, b int) string {
    return ad.SpecialRequest(a, b)
}

// 被适配器
type Adaptee interface {
    SpecialRequest(int, int) string
}

type AdapteeImpl struct {
}

// 工厂函数
func NewAdaptee() Adaptee {
    return &AdapteeImpl{}
}

// 实际函数
func (ad *AdapteeImpl) SpecialRequest(a, b int) string {
    fmt.Println(a, b)
    return "Special Request"
}

func main() {
    adapee := NewAdaptee() // 适配器
    target := NewAdapter(adapee)
    res := target.Request(1, 2)
    fmt.Println(res)
}

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go