Skip to content

Commit

Permalink
add strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
senghoo committed Apr 4, 2016
1 parent a4d9765 commit 77e7b0a
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
4 changes: 4 additions & 0 deletions 15_strategy/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# 策略模式

定义一系列算法,让这些算法在运行时可以互换,使得分离算法,符合开闭原则。

39 changes: 39 additions & 0 deletions 15_strategy/strategy.go
Original file line number Diff line number Diff line change
@@ -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)

}
15 changes: 15 additions & 0 deletions 15_strategy/strategy_test.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 77e7b0a

Please sign in to comment.