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

微笑、不失礼 提交于 2019-11-26 16:51:22

适配器模式:

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

对象适配器:

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

package mainimport "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()}

类适配器:

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

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

package maintype Target interface {    request()}type Adaptee struct {}func(it *Adaptee)specificRequest(){}type Adapter struct {   Adaptee}func(it *Adapter)request(){   it.specificRequest()}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!