dongshi4078 2017-09-17 15:06
浏览 8
已采纳

对象组件能否以复合模式彼此对话?

I am trying to implement composite design pattern. I understood how to compose an object of object. In this example I have an athlete and the swim function.

type Athlete struct {
    name string
}

type CompositeAthlete struct {
    athlete Athlete
    Train   func(name string)
}

But if I need to pass the name after composed object creation:

    comp := CompositeAthlete{
        athlete: athlete,
        Train:   Swim,
    }
    comp.Train(athlete.name)

Is it possible to inject a method that is able to read inside the object where is injected;

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)
}

I would like that comp as composed object should not receive name from outside, but from athlete. IS it possible?

  • 写回答

1条回答 默认 最新

  • douan7601 2017-09-17 18:52
    关注

    Yes, it is possible.

    You can declare a Train() method for CompositeAthlete, and that method would have access to all CompositeAthlete fields (the function and the athlete).

    Then you can use the function from inside the method.

    Here's how you'd implement it, to make it more clear.

    CompositeAthlete definition

    (note that I have changed the field to TrainFunc so that it does not conflict with the method name)

    type CompositeAthlete struct {
        athlete Athlete
        TrainFunc   func(name string)
    }
    

    Then the Train() method would just do:

    func (c *CompositeAthlete) Train() {
        c.TrainFunc(c.athlete.name)
    }
    

    And you would use it almost the same as before (only the field name has changed):

    comp := CompositeAthlete{
        athlete: athlete,
        TrainFunc:   Swim,
    }
    comp.Train()
    

    See it working in this playground:

    https://play.golang.org/p/xibH_tFers

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料