天天看点

go 设计模式之策略模式

package main

import "fmt"
//策略模式总结
//定义一个上下文的类,里面的策略元素被策略接口限制。
//实现不同的策略类
//调用的时候把策略类实例作为参数传递进去,然后调用。
//对扩展开放,对修改关闭
//实现上下文的类
type Context struct {
    Strategy Strategy
}

func NewContext(Strategy Strategy) *Context {
    return &Context{
        Strategy: Strategy,
    }
}

//抽象的策略
type Strategy interface {
    Do()
}

//实现具体的策略1
type Strategy1 struct {
}

func (s *Strategy1) Do() {
    fmt.Println("具体的策略1")
}

//实现具体的策略2
type Strategy2 struct {
}

func (s *Strategy2) Do() {
    fmt.Println("具体的策略2")
}

//具体的实现策略三
type Strategy3 struct {
}

func (s *Strategy3) Do() {
    fmt.Println("具体的策略3")
}

func Strategy1Fun() {
    context := NewContext(&Strategy1{})
    //策略1
    context.Strategy.Do()
}
func Strategy2Fun() {
    //策略2
    context2 := NewContext(&Strategy2{})
    context2.Strategy.Do()
}
func main() {
    Strategy1Fun()
    Strategy2Fun()

}      

继续阅读