1.首先定義接口,所有的策略都是基於一套標准,這樣策略(類)才有可替換性。聲明一個計算策略接口
1 package strategy 2 3 type ICompute interface { 4 Compute(a, b int) int 5 }
2.接着兩個接口實現類。復習golang語言實現接口是非侵入式設計。
1 package strategy 2 3 type Add struct { 4 } 5 6 func (p *Add) Compute(a, b int) int { 7 return a + b 8 }
1 package strategy 2 3 type Sub struct { 4 } 5 6 func (p *Sub) Compute(a, b int) int { 7 return a - b 8 }
3.聲明一個策略類。復習golang中規定首字母大寫是public,小寫是private。如果A,B改為小寫a,b,在客戶端調用時會報unknown field 'a' in struct literal of type strategy.Context
1 package strategy 2 3 var compute ICompute 4 5 type Context struct { 6 A, B int 7 } 8 9 func (p *Context) SetContext(o ICompute) { 10 compute = o 11 } 12 13 func (p *Context) Result() int { 14 return compute.Compute(p.A, p.B) 15 }
4.客戶端調用
1 package main 2 3 import ( 4 "fmt" 5 "myProject/StrategyDemo/strategy" 6 ) 7 8 func main() { 9 c := strategy.Context{A: 15, B: 7} 10 // 用戶自己決定使用什么策略 11 c.SetContext(new(strategy.Add)) 12 fmt.Println(c.Result()) 13 }

