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()

}

 

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1 Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...