Skip to content

Commit a65ccbb

Browse files
dhlinsenghoo
authored andcommitted
segregate payment context and strategy
previous PaymentContext includes PaymentStrategy, it could lead to undesired recursive calls in interface PaymentStrategy.Pay(*PaymentContext)
1 parent 55b747d commit a65ccbb

File tree

2 files changed

+19
-13
lines changed

2 files changed

+19
-13
lines changed

15_strategy/strategy.go

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,29 @@ package strategy
22

33
import "fmt"
44

5+
type Payment struct {
6+
context *PaymentContext
7+
strategy PaymentStrategy
8+
}
9+
510
type PaymentContext struct {
611
Name, CardID string
712
Money int
8-
payment PaymentStrategy
913
}
1014

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,
15+
func NewPayment(name, cardid string, money int, strategy PaymentStrategy) *Payment {
16+
return &Payment{
17+
context: &PaymentContext{
18+
Name: name,
19+
CardID: cardid,
20+
Money: money,
21+
},
22+
strategy: strategy,
1723
}
1824
}
1925

20-
func (p *PaymentContext) Pay() {
21-
p.payment.Pay(p)
26+
func (p *Payment) Pay() {
27+
p.strategy.Pay(p.context)
2228
}
2329

2430
type PaymentStrategy interface {

15_strategy/strategy_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
package strategy
22

33
func ExamplePayByCash() {
4-
ctx := NewPaymentContext("Ada", "", 123, &Cash{})
5-
ctx.Pay()
4+
payment := NewPayment("Ada", "", 123, &Cash{})
5+
payment.Pay()
66
// Output:
77
// Pay $123 to Ada by cash
88
}
99

1010
func ExamplePayByBank() {
11-
ctx := NewPaymentContext("Bob", "0002", 888, &Bank{})
12-
ctx.Pay()
11+
payment := NewPayment("Bob", "0002", 888, &Bank{})
12+
payment.Pay()
1313
// Output:
1414
// Pay $888 to Bob by bank account 0002
1515
}

0 commit comments

Comments
 (0)