From 77e7b0a2e46b67eeede7dfcf24a5d1c266a34ce2 Mon Sep 17 00:00:00 2001 From: Senghoo Kim Date: Mon, 4 Apr 2016 10:25:28 +0800 Subject: [PATCH] add strategy --- 15_strategy/README.md | 4 ++++ 15_strategy/strategy.go | 39 ++++++++++++++++++++++++++++++++++++ 15_strategy/strategy_test.go | 15 ++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 15_strategy/README.md create mode 100644 15_strategy/strategy.go create mode 100644 15_strategy/strategy_test.go diff --git a/15_strategy/README.md b/15_strategy/README.md new file mode 100644 index 0000000..3cf9802 --- /dev/null +++ b/15_strategy/README.md @@ -0,0 +1,4 @@ +# 策略模式 + +定义一系列算法,让这些算法在运行时可以互换,使得分离算法,符合开闭原则。 + diff --git a/15_strategy/strategy.go b/15_strategy/strategy.go new file mode 100644 index 0000000..85d10a1 --- /dev/null +++ b/15_strategy/strategy.go @@ -0,0 +1,39 @@ +package strategy + +import "fmt" + +type PaymentContext struct { + Name, CardID string + Money int + payment PaymentStrategy +} + +func NewPaymentContext(name, cardid string, money int, payment PaymentStrategy) *PaymentContext { + return &PaymentContext{ + Name: name, + CardID: cardid, + Money: money, + payment: payment, + } +} + +func (p *PaymentContext) Pay() { + p.payment.Pay(p) +} + +type PaymentStrategy interface { + Pay(*PaymentContext) +} + +type Cash struct{} + +func (*Cash) Pay(ctx *PaymentContext) { + fmt.Printf("Pay $%d to %s by cash", ctx.Money, ctx.Name) +} + +type Bank struct{} + +func (*Bank) Pay(ctx *PaymentContext) { + fmt.Printf("Pay $%d to %s by bank account %s", ctx.Money, ctx.Name, ctx.CardID) + +} diff --git a/15_strategy/strategy_test.go b/15_strategy/strategy_test.go new file mode 100644 index 0000000..1564024 --- /dev/null +++ b/15_strategy/strategy_test.go @@ -0,0 +1,15 @@ +package strategy + +func ExamplePayByCash() { + ctx := NewPaymentContext("Ada", "", 123, &Cash{}) + ctx.Pay() + // Output: + // Pay $123 to Ada by cash +} + +func ExamplePayByBank() { + ctx := NewPaymentContext("Bob", "0002", 888, &Bank{}) + ctx.Pay() + // Output: + // Pay $888 to Bob by bank account 0002 +}