forked from senghoo/golang-design-pattern
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
# 策略模式 | ||
|
||
定义一系列算法,让这些算法在运行时可以互换,使得分离算法,符合开闭原则。 | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |