命令模式Golang

命令模式

命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式.
请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令.

优点 和 缺点

优点:

  1. 降低系统的耦合度。命令模式能将调用操作的对象与实现该操作的对象解耦.

缺点:

  1. 使用命令模式可能会导致某些系统有过多的具体命令类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
type Stock struct {
name string
quantity int
}

func (stock *Stock) Set(name string, quantity int) {
stock.name = name
stock.quantity = quantity
}

func (stock *Stock) Buy(s Stock) {
stock.name = s.name
stock.quantity = s.quantity
fmt.Printf("Buy stock %s, quantity:%d \n", s.name, s.quantity)
}
func (stock Stock) Sell(s Stock) {
stock.name = s.name
stock.quantity = s.quantity
fmt.Printf("Sell stock %s, quantity:%d \n", s.name, s.quantity)
}
type Order interface {
Execute()
}
type BuyStock struct {
stock Stock
}

func (buy BuyStock) Execute() {
fmt.Println("execute in buy command")
buy.stock.Buy(buy.stock)
}

type SellStock struct {
stock Stock
}

func (sell SellStock) Execute() {
fmt.Println("execute in sell command")
sell.stock.Sell(sell.stock)
}

type Broker struct {
order Order
}

func (broker *Broker) SetOrder(order Order) {
fmt.Printf("set order:%v\n", order)
broker.order = order
}
func (broker Broker) Call() {
fmt.Println("call in broker")
broker.order.Execute()
}

Powered by Hexo and Hexo-theme-hiker

Copyright © 2018 - 2021 Noonde All Rights Reserved.

UV : | PV :