Skip to content

Commit 77e7b0a

Browse files
committed
add strategy
1 parent a4d9765 commit 77e7b0a

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

15_strategy/README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# 策略模式
2+
3+
定义一系列算法,让这些算法在运行时可以互换,使得分离算法,符合开闭原则。
4+

15_strategy/strategy.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package strategy
2+
3+
import "fmt"
4+
5+
type PaymentContext struct {
6+
Name, CardID string
7+
Money int
8+
payment PaymentStrategy
9+
}
10+
11+
func NewPaymentContext(name, cardid string, money int, payment PaymentStrategy) *PaymentContext {
12+
return &PaymentContext{
13+
Name: name,
14+
CardID: cardid,
15+
Money: money,
16+
payment: payment,
17+
}
18+
}
19+
20+
func (p *PaymentContext) Pay() {
21+
p.payment.Pay(p)
22+
}
23+
24+
type PaymentStrategy interface {
25+
Pay(*PaymentContext)
26+
}
27+
28+
type Cash struct{}
29+
30+
func (*Cash) Pay(ctx *PaymentContext) {
31+
fmt.Printf("Pay $%d to %s by cash", ctx.Money, ctx.Name)
32+
}
33+
34+
type Bank struct{}
35+
36+
func (*Bank) Pay(ctx *PaymentContext) {
37+
fmt.Printf("Pay $%d to %s by bank account %s", ctx.Money, ctx.Name, ctx.CardID)
38+
39+
}

15_strategy/strategy_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package strategy
2+
3+
func ExamplePayByCash() {
4+
ctx := NewPaymentContext("Ada", "", 123, &Cash{})
5+
ctx.Pay()
6+
// Output:
7+
// Pay $123 to Ada by cash
8+
}
9+
10+
func ExamplePayByBank() {
11+
ctx := NewPaymentContext("Bob", "0002", 888, &Bank{})
12+
ctx.Pay()
13+
// Output:
14+
// Pay $888 to Bob by bank account 0002
15+
}

0 commit comments

Comments
 (0)