2017-09-17 14 views
0

私は複合デザインパターンを実装しようとしています。私はオブジェクトのオブジェクトをどのように構成するのかを理解していました。この例では、アスリートと水泳機能を持っています。オブジェクトコンポーネントは、コンポジットパターンで互いに話すことができますか?

type Athlete struct { 
    name string 
} 

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

しかし、私は構成オブジェクトの作成後に名前を渡す必要がある場合:

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

注入されたオブジェクトの内部読み取ることができる方法を注入することが可能です。

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が、アスリートからをしたいと思います。出来ますか?

答えて

1

はい、可能です。

CompositeAthleteTrain()メソッドを宣言でき、そのメソッドはすべてのCompositeAthleteフィールド(関数とathlete)にアクセスできます。

次に、このメソッドの中から関数を使用できます。

これを具体的にどのように実装して、より明確にするかを説明します。

CompositeAthlete定義

(それがメソッド名と競合しないように、私はTrainFuncにフィールドを変更していることに注意してください)

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

その後Train()方法は、単に行うだろう:

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

あなたはこれまでとほとんど同じです(フィールドnaのみ私は)変更されました:

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

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

それがこの運動場で働いて参照してください。

関連する問題