Expand file tree Collapse file tree 2 files changed +19
-13
lines changed Original file line number Diff line number Diff line change @@ -2,23 +2,29 @@ package strategy
2
2
3
3
import "fmt"
4
4
5
+ type Payment struct {
6
+ context * PaymentContext
7
+ strategy PaymentStrategy
8
+ }
9
+
5
10
type PaymentContext struct {
6
11
Name , CardID string
7
12
Money int
8
- payment PaymentStrategy
9
13
}
10
14
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 ,
17
23
}
18
24
}
19
25
20
- func (p * PaymentContext ) Pay () {
21
- p .payment .Pay (p )
26
+ func (p * Payment ) Pay () {
27
+ p .strategy .Pay (p . context )
22
28
}
23
29
24
30
type PaymentStrategy interface {
Original file line number Diff line number Diff line change 1
1
package strategy
2
2
3
3
func ExamplePayByCash () {
4
- ctx := NewPaymentContext ("Ada" , "" , 123 , & Cash {})
5
- ctx .Pay ()
4
+ payment := NewPayment ("Ada" , "" , 123 , & Cash {})
5
+ payment .Pay ()
6
6
// Output:
7
7
// Pay $123 to Ada by cash
8
8
}
9
9
10
10
func ExamplePayByBank () {
11
- ctx := NewPaymentContext ("Bob" , "0002" , 888 , & Bank {})
12
- ctx .Pay ()
11
+ payment := NewPayment ("Bob" , "0002" , 888 , & Bank {})
12
+ payment .Pay ()
13
13
// Output:
14
14
// Pay $888 to Bob by bank account 0002
15
15
}
0 commit comments