首页 > 其他 > 详细

go 设计模式之策略模式

时间:2021-05-16 19:21:32      阅读:35      评论:0      收藏:0      [点我收藏+]
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 设计模式之策略模式

原文:https://www.cnblogs.com/zxqblogrecord/p/14773868.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!