From 02323f814f3c9f7de9bb58f9983198b32319c58f Mon Sep 17 00:00:00 2001 From: ismayilmalik Date: Sat, 20 Jan 2018 13:07:56 +0300 Subject: [PATCH] command pattern error fix --- behavioral/command/command.go | 64 +++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 behavioral/command/command.go diff --git a/behavioral/command/command.go b/behavioral/command/command.go new file mode 100644 index 0000000..1a71cdd --- /dev/null +++ b/behavioral/command/command.go @@ -0,0 +1,64 @@ +package command + +import ( + "fmt" +) + +type Order interface { + execute() +} + +type Stock struct { + name string + count int +} +func (s *Stock) Buy() { + fmt.Println("Bought new item.") + s.count += 1 +} +func (s *Stock) Sell() { + fmt.Println("Sold one item.") + s.count -= 1 +} + +type BuyStock struct { + stock Stock +} +func (b *BuyStock) execute() { + b.stock.Buy() +} + +type SellStock struct { + stock Stock +} +func (b *SellStock) execute() { + b.stock.Sell() +} + +type Broker struct { + orders []Order +} +func (b *Broker) TakeOrder(o Order) { + b.orders = append(b.orders, o) +} +func (b *Broker) PlaceOrders() { + for _,v := range b.orders { + v.execute() + } + + b.orders = make([]Order, 0) +} + +func Demo() { + stock := Stock{name:"phone", count:2} + buyStck := &BuyStock{stock} + sellStck := &SellStock{stock} + broker := &Broker{} + broker.orders = make([]Order, 0) + + broker.TakeOrder(buyStck) + broker.TakeOrder(sellStck) + + broker.PlaceOrders() + +} \ No newline at end of file