我正在尝试实现复合设计模式。我了解了如何组合对象的对象。在这个例子中,我有一个运动员和游泳功能。
type Athlete struct {
name string
}
type CompositeAthlete struct {
athlete Athlete
Train func(name string)
}
但是如果我需要在创建组合对象后传递名称:
comp := CompositeAthlete{
athlete: athlete,
Train: Swim,
}
comp.Train(athlete.name)
是否有可能注入(inject)一个能够读取被注入(inject)对象内部的方法;
package main
import (
"fmt"
"strings"
)
type Athlete struct {
name string
}
type CompositeAthlete struct {
athlete Athlete
Train func(name string)
}
func (a *Athlete) Train() {
fmt.Println("training ...")
}
func Swim(name string) {
fmt.Println(strings.Join([]string{
name,
" is swimming",
}, ""))
}
func main() {
fmt.Println("vim-go")
athlete := Athlete{"Mariottide"}
athlete.Train()
comp := CompositeAthlete{
athlete: athlete,
Train: Swim,
}
comp.Train(athlete.name)
}
我希望 comp
作为组合对象不应该从外部接收名称,而是从运动员那里接收名称。可能吗?
最佳答案
是的,这是可能的。
您可以为 CompositeAthlete
声明一个 Train()
方法,该方法可以访问所有 CompositeAthlete
字段(函数和运动员
).
然后您可以在方法内部使用函数。
以下是您将如何实现它,以使其更加清晰。
CompositeAthlete 定义
(注意,我把字段改成了TrainFunc
,这样才不会和方法名冲突)
type CompositeAthlete struct {
athlete Athlete
TrainFunc func(name string)
}
然后 Train()
方法会做:
func (c *CompositeAthlete) Train() {
c.TrainFunc(c.athlete.name)
}
而且你会像以前一样使用它(只是字段名称发生了变化):
comp := CompositeAthlete{
athlete: athlete,
TrainFunc: Swim,
}
comp.Train()
看到它在这个 Playground 上工作:
关于go - go 对象组件可以以复合模式相互通信吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46265534/