go知识重新整理

This commit is contained in:
Estom
2021-09-03 05:34:34 +08:00
parent 62309f856a
commit 1bad082e49
291 changed files with 29345 additions and 2 deletions

View File

@@ -0,0 +1,56 @@
/**
* @Author:zhoutao
* @Date:2020/12/12 下午1:50
* @Desc:
*/
package strategy
import "fmt"
//策略模式:定义一系列算法,让这些算法在运行时可以互换,使得算法分离,符合开闭原则
type PaymentContext struct {
Name, CardID string
Money int
}
func NewPayment(name, cardID string, money int, strategy PaymentStrategy) *Payment {
return &Payment{
context: &PaymentContext{
Name: name,
CardID: cardID,
Money: money,
},
strategy: strategy,
}
}
type Payment struct {
context *PaymentContext
strategy PaymentStrategy
}
func (p *Payment) Pay() {
p.strategy.Pay(p.context)
}
type PaymentStrategy interface {
Pay(*PaymentContext)
}
//by cash
type Cash struct {
}
func (*Cash) Pay(ctx *PaymentContext) {
fmt.Printf("Pay $%d to %s by cash", ctx.Money, ctx.Name)
}
//by Bank
type Bank struct {
}
func (*Bank) Pay(ctx *PaymentContext) {
fmt.Printf("Pay $%d to %s by Bank", ctx.Money, ctx.Name)
}

View File

@@ -0,0 +1,20 @@
/**
* @Author:zhoutao
* @Date:2020/12/12 下午2:06
* @Desc:
*/
package strategy
func ExamplePayByCash() {
payment := NewPayment("ad", "808490523", 900, &Cash{})
payment.Pay()
//Output:
//Pay by cash
}
func ExamplePayByBank() {
payment := NewPayment("tom", "345782345", 900, &Bank{})
payment.Pay()
}