implemented mediator pattern

This commit is contained in:
ismayilmalik 2018-01-16 00:53:06 +03:00
parent 43ba305859
commit 1ea149edd8
3 changed files with 77 additions and 2 deletions

View File

@ -86,5 +86,11 @@ Define a one-to-many dependency between objects so that when one object changes
### State
Allow an object alter its behavior when its internal state changes. The object will appear on change its class
### Visitor
Represent an operation to be performed on the elements of an object structure.Visitor lets you define new operation without changing the classes of the elements of which operates
### Mediator
Define an object that encapsulates how a set of objects interact.Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently
## Concurrency patterns
Pattenrs for concurrent work and parallel execution in Go.

View File

@ -0,0 +1,68 @@
package mediator
import (
"fmt"
"errors"
)
// Mediator
type TradeService struct {
Orders []Order
}
func (t *TradeService) GetOrders(orderType string) ([]Order, error) {
orders := make([]Order, 0)
if orderType != "buy" || orderType != "sell" {
return orders, errors.New("Invalid order type provided.")
}
for _, v := range t.Orders {
if v.OrderType == orderType {
orders = append(orders, v)
}
}
return orders, nil
}
func (t *TradeService) PushOrder(o Order) {
// We dont need too much logic to show the purpose of the pattern
t.Orders = append(t.Orders, o)
}
type Order struct {
OrderType string
Price float32
}
type Trader struct {
Service *TradeService
OrderToPlace Order
InterestedOrders []Order
}
func (t *Trader) PlaceOrder() {
t.Service.PushOrder(t.OrderToPlace)
}
func (t *Trader) GetOrders(orderType string) {
t.InterestedOrders, _ = t.Service.GetOrders(orderType)
}
func Demo () {
tradeService := &TradeService{}
tradeService.Orders = make([]Order, 0)
traderOne := &Trader{ Service: tradeService}
traderOne.OrderToPlace = Order{ "buy", 1.2 }
traderOne.PlaceOrder()
traderTwo := &Trader{ Service: tradeService}
traderTwo.OrderToPlace = Order{ "sell", 1.5 }
traderOne.PlaceOrder()
traderOne.GetOrders("sell")
fmt.Println(traderOne.InterestedOrders)
traderTwo.GetOrders("buy")
fmt.Println(traderTwo.InterestedOrders)
}

View File

@ -4,6 +4,7 @@ import (
"fmt"
)
// Abstractions ...
type Visitor interface {
VisitProductWithHighTask(ProductWithHighTax) float32
VisitProductWithLowTask(ProductWithLowTax) float32
@ -13,18 +14,18 @@ type Visitable interface {
Accept(Visitor) float32
}
// Visitor
type TaxVisitor struct {}
func (v TaxVisitor) VisitProductWithHighTask(p ProductWithHighTax) float32 {
fmt.Println("Visiting Product With High Tax ...")
return p.Price * 1.3
}
func (v TaxVisitor) VisitProductWithLowTask(p ProductWithLowTax) float32 {
fmt.Println("Visiting Product With Low Tax ...")
return p.Price * 1.1
}
// Visitable objects...
type ProductWithHighTax struct {
Price float32
}