首页 > 其他分享 >【转】Command Pattern in Go (Golang)

【转】Command Pattern in Go (Golang)

时间:2024-03-12 13:58:51浏览次数:17  
标签:execute dishes restaurant Pattern Restaurant cooks Command Go

 

原文: https://www.sohamkamani.com/golang/command-pattern/

 

package main

import "fmt"

// The restaurant contains the total dishes and the total cleaned dishes
type Restaurant struct {
	TotalDishes   int
	CleanedDishes int
}

// `NewRestaurant` constructs a new restaurant instance with 10 dishes,
// all of them being clean
func NewResteraunt() *Restaurant {
	const totalDishes = 10
	return &Restaurant{
		TotalDishes:   totalDishes,
		CleanedDishes: totalDishes,
	}
}

func (r *Restaurant) MakePizza(n int) Command {
	return &MakePizzaCommand{
		restaurant: r,
		n:          n,
	}
}

func (r *Restaurant) MakeSalad(n int) Command {
	return &MakeSaladCommand{
		restaurant: r,
		n:          n,
	}
}

func (r *Restaurant) CleanDishes() Command {
	return &CleanDishesCommand{
		restaurant: r,
	}
}

type Command interface {
	execute()
}

// The MakePizzaCommand is a struct which contains
// the number of pizzas to make, as well as the
// restaurant as its attributes
type MakePizzaCommand struct {
	n          int
	restaurant *Restaurant
}

func (c *MakePizzaCommand) execute() {
	// Reduce the total clean dishes of the restaurant
	// and print a message once done
	c.restaurant.CleanedDishes -= c.n
	fmt.Println("made", c.n, "pizzas")
}

// The MakeSaladCommand is similar to the MakePizza command
type MakeSaladCommand struct {
	n          int
	restaurant *Restaurant
}

func (c *MakeSaladCommand) execute() {
	c.restaurant.CleanedDishes -= c.n
	fmt.Println("made", c.n, "salads")
}

type CleanDishesCommand struct {
	restaurant *Restaurant
}

func (c *CleanDishesCommand) execute() {
	// Reset the cleaned dishes to the total dishes
	// present, and print a message once done
	c.restaurant.CleanedDishes = c.restaurant.TotalDishes
	fmt.Println("dishes cleaned")
}

// A Cook comes with their list of commands as attributes
type Cook struct {
	Commands []Command
}

// The executeCommands method executes all the commands
// one by one
func (c *Cook) executeCommands() {
	for _, c := range c.Commands {
		c.execute()
	}
}

func main() {
	// initialize a new resaurant
	r := NewResteraunt()

	// create the list of tasks to be executed
	tasks := []Command{
		r.MakePizza(2),
		r.MakeSalad(1),
		r.MakePizza(3),
		r.CleanDishes(),
		r.MakePizza(4),
		r.CleanDishes(),
	}

	// create the cooks that will execute the tasks
	cooks := []*Cook{
		&Cook{},
		&Cook{},
	}

	// Assign tasks to cooks alternating between the existing
	// cooks.
	for i, task := range tasks {
		// Using the modulus of the current task index, we can
		// alternate between different cooks
		cook := cooks[i%len(cooks)]
		cook.Commands = append(cook.Commands, task)
	}

	// Now that all the cooks have their commands, we can call
	// the `executeCommands` method that will have each cook
	// execute their respective commands
	for i, c := range cooks {
		fmt.Println("cook", i, ":")
		c.executeCommands()
	}
}

  

--------------------

 

Command Pattern in Go (Golang)

November 27, 2019 · Written by Soham Kamani

This article will explain the command pattern, where to use it, and how to implement it in Go.

The command pattern, as the name suggests, is used when we want to create and execute “commands”. Different commands have their own implementation, but have the same steps for execution.

The Command Interface

The basic unit for implementing the command pattern is the Command interface:

type Command interface {
	execute()
}

If the command can error out, the interface can contain an error return value as well:

type Command interface {
	execute() error
}

标签:execute,dishes,restaurant,Pattern,Restaurant,cooks,Command,Go
From: https://www.cnblogs.com/oxspirt/p/18068129

相关文章

  • 一键开启 GPU 闲置模式,基于函数计算低成本部署Google Gemma 模型服务
    背景信息Google在2024年02月21日正式推出了自家的首个开源模型族Gemma,并同时上架了四个大型语言模型,提供了2B和7B两种参数规模的版本,每种都包含了预训练版本(base模型)和指令微调版本(chat模型)。根据Google的技术报告,本次开源的Gemma在问题回答、合理性、数学、代码......
  • [转]Golang Functional Options Pattern
     原文: https://golang.cafe/blog/golang-functional-options-pattern.html-------------------- GolangFunctionalOptionsPatternTheGo(Golang)FunctionaOptionsPatternisaway,apatternofstructuringyourstructsinGobydesigningaveryexpressivea......
  • Total Commander(TC)批量切换标签的方法
      2人赞同了该文章TC能否批量切换标签?比如:工作场景下,打开多个与工作场景相关的文件夹标签;学习场景下,需要打开多个与学习场景相关的文件夹标签。这些文件夹标签分别组成【工作标签组】和【学习标签组】。能否实现【工作标签组】和【学习标签组】之间的切换呢?答案是肯......
  • Go 语言开发环境搭建
    Go语言开发环境搭建Go语言开发环境搭建一.GO环境安装1.1下载Go官网:https://golang.org/dl/Go镜像站(推荐):https://golang.google.cn/dl/1.2Go版本的选择默认下载最新自己对应的平台即可。  1.3安装1.3.1Windows安装打开下载的安装程序(.msi文件),然后按照......
  • Mac安装MongoDB
    本文是简单的安装步骤1.下载[MongoDB]社区版本5(https://www.mongodb.com/zh-cn)2.解压,重命名为mongodb,访达中使用command+shift+G搜索进入/user/local/,文件夹放在这里3.环境变量配置终端运行:open.bash_profile(没有的话在终端上创建touch.bash_profile)打开的文件中:expo......
  • golang练习题
    看到一个网站,上面每天发布一道golang练习题,正好拿来练习,顺便整理记录下来。iota,类似枚举值,每个const从0开始计数 String方法相当于java里的toStringgolang处于安全考虑,对指针运算做了很多限制。map的value是不可以取地址的。 ......
  • Django请求生命周期流程图
    Django请求生命周期流程图流程如下:浏览器发送请求(Http请求)web服务网关接口(Django默认的wsgiref模块不能承受高并发,最大只有1000左右)中间件>>缓存数据库(返回给中间件已经缓存过的数据)urls.py(路由层)views.py(视图层)templates(模板层:存放html静态......
  • Django
    Django配置与创建(1)创建Django项目django-adminstartproject文件名(2)启动Django文件pythonmanage.pyrunserver(3)创建apppythonmanage.pystartapp应用名#pythonmanage.pystartappapp01(4)注册app创建app后,如果想使用相关的功能,必须将创建的app注册到配置文件中......
  • Django模板语法
    Django模版语法(1)传数据模版语法可以传递的后端python数据类型(可迭代)后端:deftest2(request):name='heart'float=11.11str_name='你好'boolean_test=Truelist_test=[1,2,3]tuple_test=(1,2,3)dict_test={'name�......
  • 10django
    作业(二次删除确认)#ajax结合sweetalert(ajax用于页面不刷新也可以提交数据,sweetalert是帮助美化删除二次确认的)1.下载源码只需要到dist文件夹内的css和js即可2.拷贝使用官网提供的案例代码3.添加配置参数新增等待特效<divclass="container"><divclass="row"......