设计模式——适配器模式

2020-11-05  本文已影响0人  DevilRoshan

什么是适配器模式?

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

实现

// Target目标角色,该角色定义把其他类转换为何种接口,也就是期望接口,通常情况下是一个接口或一个抽象类,一般不会是实现类。
type Target interface {
    Request()
}

// Adaptee源角色,想把谁转换为目标角色,这个“谁”就是源角色,它是已经存在的、运行良好的类或对象。
type Adaptee struct {
    
}

func (this *Adaptee)SpecificRequest()  {
    fmt.Println("特殊请求")
}

// Adapter适配器角色,是适配器模式的核心角色,它的职责是通过继承或是类关联的方式把源角色转换为目标角色。
type Adapter struct {
    *Adaptee
}


func NewAdapter() *Adapter  {
    return &Adapter{}
}

func (this *Adapter)request()  {
    this.SpecificRequest()
}

// 目标角色的实现类。
type ConcreteTarget struct {
}

func NewConcreteTarget() *ConcreteTarget  {
    return &ConcreteTarget{}
}

func (this *ConcreteTarget)request()  {
    fmt.Println("普通请求")
}
func TestNewAdapter(t *testing.T) {
    target1 := NewConcreteTarget()
    target1.request()

    target2 := NewAdapter()
    target2.request()
}
/*
=== RUN   TestNewAdapter
普通请求
特殊请求
--- PASS: TestNewAdapter (0.00s)
PASS
*/

优点

缺点

使用场景

注意

上一篇 下一篇

猜你喜欢

热点阅读