行为-策略模式

192 阅读1分钟

1、概述

简介: 一类的行为或算法可以在运行的时候更改,这种类型的设计属于 行为模式 的一种

特点:

  1. 依赖关系:一个策略接口 ,一个环境对象。环境对象使用策略接口。
  2. 实现关系:不同的策略都实现 同一个 策略接口

参考:策略模式

2、代码实现


package main

import "fmt"

//销售策略
type SellStrategy interface {
	GetPrice(price float64) float64
}


// A
type StrategyA struct {
}

func (sa *StrategyA) GetPrice(price float64) float64 {
	fmt.Println("执行策略A")
	return price * 0.8
}

//B
type StrategyB struct {
}

func (sb *StrategyB) GetPrice(price float64) float64 {
	fmt.Println("执行策略A")

	if price >= 200 {
		price -= 100
	}

	return price
}

//环境类
type Goods struct {
	Price    float64
	Strategy SellStrategy
}

func (g *Goods) SetStrategy(s SellStrategy) {
	g.Strategy = s
}

func (g *Goods) SellPrice() float64 {
	return g.Strategy.GetPrice(g.Price)
}

func main() {
	nike := Goods{
		Price: 200.0,
	}

	fmt.Printf("nike: %v\n", nike)

	//A
	nike.SetStrategy(new(StrategyA))
	fmt.Println("上午Nike 价格", nike.SellPrice())

	fmt.Printf("nike1: %v\n", nike)

	//B
	nike.SetStrategy(new(StrategyB))
	fmt.Println("下午Nike 价格", nike.SellPrice())

	fmt.Printf("nike2: %v\n", nike)

}