策略模式-Golang实现

栏目: Go · 发布时间: 7年前

内容简介:目的:根据不同策略来执行对象的相应操作和工厂模式很像,不同点在于:工厂模式是传入参数后创建对象,根据传入的参数写逻辑来判断应该创建什么类型的对象,模式的使用者调用对象统一的方法操作。

目的:根据不同策略来执行对象的相应操作

和工厂模式很像,不同点在于:

工厂模式是传入参数后创建对象,根据传入的参数写逻辑来判断应该创建什么类型的对象,模式的使用者调用对象统一的方法操作。

策略模式是模式的使用者必须先创建好对象,将该对象作为参数传进去,然后通过该对象调用相应的方法。

设计场景如下:

吃饭的时候,我们有三种主食可以选,米饭、面包和苗条。

golang实现代码:

package strategypattern

import "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()
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Beautiful Code

Beautiful Code

Greg Wilson、Andy Oram / O'Reilly Media / 2007-7-6 / GBP 35.99

In this unique work, leading computer scientists discuss how they found unusual, carefully designed solutions to difficult problems. This book lets the reader look over the shoulder of major coding an......一起来看看 《Beautiful Code》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换