Design patterns

The strategy pattern

The policy pattern defines a set of algorithm classes and encapsulates each algorithm individually so that they can be replaced with each other. The policy pattern makes the algorithm independent of the client. The policy pattern is used to decouple the definition, creation, and use of policies. Generally speaking, the policy pattern also contains three parts: define, create, and use.

The strategy mode is a little bit like the factory mode, but with the strategy part,

Using the scenario

  • The most common scenario for the policy pattern is to use it to avoid verboseif-elseOr switch branch judgment
  • It does more than that, providing extension points to the framework as well as the template pattern.
  • The main role of policy patterns is to decouple the definition, creation, use, and complexity of policies

code

package strategy

import "fmt"

type Payment struct {
	context  *PaymentContext
	strategy PaymentStrategy
}

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,
	}
}

func (p *Payment) Pay() {
	p.strategy.Pay(p.context)
}

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)

}
Copy the code

test

package strategy

func ExamplePayByCash() {
	payment := NewPayment("Ada", "", 123, &Cash{})
	payment.Pay()
	// Output:
	// Pay $123 to Ada by cash
}

func ExamplePayByBank() {
	payment := NewPayment("Bob", "0002", 888, &Bank{})
	payment.Pay()
	// Output:
	// Pay $888 to Bob by bank account 0002
}

Copy the code

Welcome to: Programmer developer community

The resources

  • Github.com/senghoo/gol…