dongshi4078 2017-09-17 07: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 10: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

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部