gof23结构类模式(golang版)

菟潞寺沙弥 · · 1243 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

适配器模式

Adapter模式也被称为Wrapper模式,有以下两种:

  1. 类适配器(使用继承)
https://design-
clipboard.png
实现目标接口,继承被适配类
  1. 对象适配器(使用委托)
clipboard.png
继承目标类,依赖被适配类

参考http://blog.51cto.com/liuxp08...

package main

import (
    "fmt"
)

func main() {
    duck := &MallardDuck{}
    turkey := &WildTurkey{}

    turkeyAdapter := NewTurkeyAdapter(turkey)

    fmt.Println("The Turkey says...")
    turkey.gobble()
    turkey.fly()

    fmt.Println("The Duck says...")
    duck.quack()
    duck.fly()

    fmt.Println("The Turkey Adapter says...")
    turkeyAdapter.quack()
    turkeyAdapter.fly()
}

type Duck interface {
    quack()
    fly()
}

type Turkey interface {
    gobble()
    fly()
}

type MallardDuck struct {
}

func (*MallardDuck) quack() {
    fmt.Println("Quark...")
}

func (*MallardDuck) fly() {
    fmt.Println("flying...")
}

type WildTurkey struct {
}

func (*WildTurkey) gobble() {
    fmt.Println("Gobble...")
}

func (*WildTurkey) fly() {
    fmt.Println("flying a short distance")
}

type TurkeyAdapter struct {
    turkey Turkey
}

func NewTurkeyAdapter(turkey Turkey) *TurkeyAdapter {
    return &TurkeyAdapter{turkey}
}

func (this *TurkeyAdapter) quack() {
    this.turkey.gobble()
}

func (this *TurkeyAdapter) fly() {
    for i := 0; i < 5; i++ {
        this.turkey.fly()
    }
}

适配器TurkeyAdpater,持有turkey Turkey,实现Duck接口。

代理模式

uml:
https://design-patterns.readt...
clipboard.png

代理模式中的成员构成:

  • Subject(主体)
  • Proxy (代理人)
  • RealSubject(实际的主体)
  • Client (请求者)

代理的目的是在目标对象方法的基础上作增强,这种增强的本质通常就是对目标对象的方法进行拦截和过滤。


有疑问加站长微信联系(非本文作者)

本文来自:Segmentfault

感谢作者:菟潞寺沙弥

查看原文:gof23结构类模式(golang版)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1243 次点击  
加入收藏 微博
下一篇:golang中bufio包
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传