结构型设计模式——适配器模式(Go)

适配器模式:

  适配器模式是用于当别人提供的对象或接口中的方法或者其它属性啥的和我们的重复了,或者看的不顺眼。名字太长了记不住,而将其包装到一个对象中,然后通过你感觉自己舒服的方式或者方法名字去间接的调用它。一个简单的例子就是三角插座,我没有三角口,用一个转接器呗。

对象适配器:

  将那个你看的不顺眼的对象的引用存在你的包装类对象内

../_images/Adapter.jpg
package main

import "fmt"

type Target interface {
request()
}
type Adaptee struct {

}
func(it *Adaptee)specificrequeset(){
fmt.Println("asdf")
}

type Adapter struct {
adaptee *Adaptee
}
func(it *Adapter)setAdaptee(adaptee *Adaptee){
it.adaptee = adaptee
}
func(it *Adapter)request(){
it.adaptee.specificrequeset()
}

func main(){
target := new(Adapter)
adaptee := new(Adaptee)
target.setAdaptee(adaptee)
target.request()
}

类适配器:

通过同时继承这两个类,而使自己拥有方法和替代方法,

在替代方法内调用原本方法

../_images/Adapter_classModel.jpg
package main

type Target interface {
request()
}
type Adaptee struct {

}
func(it *Adaptee)specificRequest(){

}
type Adapter struct {
Adaptee
}
func(it *Adapter)request(){
it.specificRequest()
}
原文地址:https://www.cnblogs.com/mcmx/p/11327365.html