策略模式-Golang实现
生活随笔
收集整理的這篇文章主要介紹了
策略模式-Golang实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目的:根據不同策略來執行對象的相應操作
和工廠模式很像,不同點在于:
工廠模式是傳入參數后創建對象,根據傳入的參數寫邏輯來判斷應該創建什么類型的對象,模式的使用者調用對象統一的方法操作。
策略模式是模式的使用者必須先創建好對象,將該對象作為參數傳進去,然后通過該對象調用相應的方法。
設計場景如下:
吃飯的時候,我們有三種主食可以選,米飯、面包和苗條。
golang實現代碼:
package strategypatternimport "fmt" /*實體類接口*/ type Staplefood interface {Eat() }type RiceStaplefood struct {}type NoodleStaplefood struct {} /*策略類*/ type EatContext struct {staplefood Staplefood }type BreadStaplefood struct {}func (RiceStaplefood) Eat(){fmt.Println("吃米飯") }func (NoodleStaplefood) Eat() {fmt.Println("吃面條") }func (BreadStaplefood) Eat() {fmt.Println("吃面包") } /*策略類操作方法*/ func (context EatContext) EatFood(){context.staplefood.Eat() } /*策略類構造函數*/ func NewEatContext(staplefood Staplefood) *EatContext{return &EatContext{staplefood:staplefood,} }func Excute(){eat := NewEatContext(new(RiceStaplefood))eat.EatFood()eat = NewEatContext(new(NoodleStaplefood))eat.EatFood()eat = NewEatContext(new(BreadStaplefood))eat.EatFood() }轉載于:https://www.cnblogs.com/linux-java/p/10185054.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的策略模式-Golang实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HttpRunner自动化框架学习笔记
- 下一篇: matlab 处理dat文件画图,mat