日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

策略模式-Golang实现

發布時間:2023/12/9 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 策略模式-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实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。