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 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持