もくじ
Switchをinterfaceを利用することで消滅させるStrategyパターン
interaface以外にもmapで同様のことができる。
type Member struct { Level int Agility int MagicAttack int Vitality int } type MagicType interface { Name() string CostMagicPoint(member Member) int AttackPower(member Member) int CostTechnicalPoint(member Member) int } type Fire struct{} type Shiden struct{} type HellFire struct{} func (Fire) Name() string { return "ファイア" } func (Fire) CostMagicPoint(member Member) int { return 2 } func (Fire) AttackPower(member Member) int { return 20 + int(float64(member.Level)*0.5) } func (Fire) CostTechnicalPoint(member Member) int { return 0 } func (Shiden) Name() string { return "紫電" } func (Shiden) CostMagicPoint(member Member) int { return 5 + int(float64(member.Level)*0.2) } func (Shiden) AttackPower(member Member) int { return 50 + int(float64(member.Agility)*1.5) } func (Shiden) CostTechnicalPoint(member Member) int { return 5 } func (HellFire) Name() string { return "地獄の業火" } func (HellFire) CostMagicPoint(member Member) int { return 16 } func (HellFire) AttackPower(member Member) int { return 200 + int(float64(member.MagicAttack)*0.5+float64(member.Vitality)*2) } func (HellFire) CostTechnicalPoint(member Member) int { return 20 + int(float64(member.Level)*0.4) } type Magic struct { MagicType MagicType Member Member } func NewMagic(magicType MagicType, member Member) *Magic { return &Magic{ MagicType: magicType, Member: member, } }
client.go
package main import "fmt" func main() { // Memberを生成します member := Member{ Level: 10, Agility: 15, MagicAttack: 20, Vitality: 30, } // Fireを使ってMagicを生成します magic := NewMagic(Fire{}, member) fmt.Println("Magic name:", magic.MagicType.Name()) fmt.Println("Magic point cost:", magic.MagicType.CostMagicPoint(magic.Member)) fmt.Println("Magic attack power:", magic.MagicType.AttackPower(magic.Member)) fmt.Println("Magic technical point cost:", magic.MagicType.CostTechnicalPoint(magic.Member)) // Shidenを使ってMagicを生成します magic = NewMagic(Shiden{}, member) fmt.Println("\nMagic name:", magic.MagicType.Name()) fmt.Println("Magic point cost:", magic.MagicType.CostMagicPoint(magic.Member)) fmt.Println("Magic attack power:", magic.MagicType.AttackPower(magic.Member)) fmt.Println("Magic technical point cost:", magic.MagicType.CostTechnicalPoint(magic.Member)) // HellFireを使ってMagicを生成します magic = NewMagic(HellFire{}, member) fmt.Println("\nMagic name:", magic.MagicType.Name()) fmt.Println("Magic point cost:", magic.MagicType.CostMagicPoint(magic.Member)) fmt.Println("Magic attack power:", magic.MagicType.AttackPower(magic.Member)) fmt.Println("Magic technical point cost:", magic.MagicType.CostTechnicalPoint(magic.Member)) }
リクエストからNewMagic()へのインジェクションはMapを使えば、switchやifを使う必要もなくなります。