mohuishou / blogComment

mohuishou's blog comment
0 stars 0 forks source link

post/template #255

Closed utterances-bot closed 2 years ago

utterances-bot commented 3 years ago

Go模板模式14-模板模式 - Mohuishou

mohuishou 的 技术博客, 关注云原生, Go, K8s, Docker, 微服务等技术

https://lailin.xyz/post/template.html

jmuwfq commented 3 years ago

// 实际使用中,我们并不会这么写,都是采用组合+接口的方式完成类似的功能 这个怎么理解

mohuishou commented 3 years ago

// 实际使用中,我们并不会这么写,都是采用组合+接口的方式完成类似的功能 这个怎么理解

模板模式一般使用继承实现,Go 当中没有继承,所以实现起来就会很绕 像示例的这种需求一般会类似策略模式的方式,定义一个发送短信的接口,具体的实现由具体的供应商 strcut 来实现就行了

jmuwfq commented 3 years ago

我觉得golang模板方法模式的关键在于父类怎么能够调用到子类的方法,如果用组合的方式就是字类调用父类的方法。如果再父类中写模板步骤的run方法,子类只能也实现了run方法,不然就用不了。这应该也是你再父类中设置接口匿名成员的原因?

mohuishou commented 3 years ago

我觉得golang模板方法模式的关键在于父类怎么能够调用到子类的方法,如果用组合的方式就是字类调用父类的方法。如果再父类中写模板步骤的run方法,子类只能也实现了run方法,不然就用不了。这应该也是你再父类中设置接口匿名成员的原因?

是的,所以类似需要继承的,其实在 Go 中都不太常用

jmuwfq commented 3 years ago

难搞,刚好使用golang,又有这种场景,固定方法步骤,部分实现相同,部分不同

jmuwfq commented 3 years ago

不知道您说的组合+继承能否实现上述的功能?能否简单给个例子呢

mohuishou commented 3 years ago

不知道您说的组合+继承能否实现上述的功能?能否简单给个例子呢

这个要看具体的需求。。。。

tutengdihuang commented 3 years ago

https://wangjiayu.blog.csdn.net/article/details/91128627 这个例子应该更好理解

zxcasd848955 commented 2 years ago

这样是不是清晰点

package templatemethod

import "fmt"

type Sender interface { // 不同供应商提供的send接口
    Send(content string, phone int) error
}

type SMS interface { // 业务流程
    valid(content string) error                             //不变的部分
    sendMessage(scontent string, phone int, s Sender) error //可变的部分
}

type SMSBussiness struct{}

func (sms SMSBussiness) valid(content string) error {
    if len(content) > 63 {
        return fmt.Errorf("content is too long")
    }
    return nil
}

func (sms SMSBussiness) sendMessage(content string, phone int, s Sender) error {
    if err := sms.valid(content); err != nil {
        return err
    }
    // 发送逻辑
    return s.Send(content, phone)
}

type TelecomSms struct{}

func (ts TelecomSms) Send(content string, phone int) error {
    fmt.Printf("Send by Telecom, phone %v, messgae %v\n", phone, content)
    return nil
}