-
Notifications
You must be signed in to change notification settings - Fork 14
/
command.go
68 lines (53 loc) · 1.08 KB
/
command.go
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"fmt"
"strconv"
)
type Order interface {
Execute()
}
type Stock struct {
name string
amount int
}
func (self *Stock) Buy() {
fmt.Println("buy " + self.name + " stock " + strconv.Itoa(self.amount) + " shares")
}
func (self *Stock) Sell() {
fmt.Println("sell " + self.name + " stock " + strconv.Itoa(self.amount) + " shares")
}
type BuyStock struct {
stock *Stock
}
func (self *BuyStock) Execute() {
self.stock.Buy()
}
type SellStock struct {
stock *Stock
}
func (self *SellStock) Execute() {
self.stock.Sell()
}
// command invoker which is going to
// take and execute request
type Broker struct {
orderList []Order
}
func (self *Broker) TakeOrder(order Order) {
self.orderList = append(self.orderList, order)
}
func (self *Broker) PlaceOrders() {
for _, order := range self.orderList {
order.Execute()
}
self.orderList = nil
}
func main() {
stock := &Stock{name: "APPL", amount: 10}
buyStock := &BuyStock{stock}
sellStock := &SellStock{stock}
broker := &Broker{}
broker.TakeOrder(buyStock)
broker.TakeOrder(sellStock)
broker.PlaceOrders()
}