设计模式-策略模式

TIP

好的文章必须要有自己的观点输出,如果自己想的不全的,或者有问题的,再查资料核对再进行补充。

定义#

TIP

认识和讲述一个事,必须要先深入理解他的概念开始

  • 诸葛亮锦囊妙计模型

赵子龙得到诸葛亮的锦囊,顺利帮助刘备让周瑜陪了夫人折了兵;其中锦囊中三个字条对应三个妙计(可以抽象继承一个接口,也可以各自是一个接口), 锦囊对应环境(context供赵云执行者使用) 总结三个角色: context封装 / strategy抽象策略 / concreteStrategy 具体策略

  • 算法模型

定义一些算法,把每个算法都封装起来,让他们之间可以相互替代 三个角色 不同的算法:concreteStrategy 实现算法的接口:strategy 相互替换 context 封装实现

  • 鸭子模型

设计原则 封装变化,让算法的变化和使用算法的客户分离开;多用组合,少用继承;

wiki

UML图#

Demo#

妙计 (结构易,实现难)#

evictionAlgo.go


package main
type evictionAlgo interface {    evict(c *cache)}

fifo.go

package main
import "fmt"
type fifo struct {
}
func (l *fifo)evict(c *cache){    fmt.Println("Evicting by fifo strategy")}

lru.go

package main
import "fmt"
type lru struct {
}
func (l *lru) evict(c *cache){        fmt.Println("Evicting by lru strategy")}

锦囊 (有套路结构难,实现易)#

cache.go


package main
type cache struct {    storage map[string]string    evictionAlgo evictionAlgo    capacity int    maxCapacity int}
func initCache(e evictionAlgo) *cache{    storage := make(map[string]string)    return &cache{        storage: storage,        evictionAlgo: e,        capacity: 0,        maxCapacity: 2,    }}
//中间件方法,对外提供一个方法给外部调用,对内调用内部的方法实现解耦func (c *cache) setEvictionAlgo(e evictionAlgo){    c.evictionAlgo = e}
func (c *cache) add(key,value string){    if c.capacity == c.maxCapacity{        c.evict()    }    c.capacity ++    c.storage[key] = value}
func (c *cache) get(key string){    delete(c.storage,key)}
func (c *cache) evict(){    c.evictionAlgo.evict(c)    c.capacity --}

使用客户#

main.go


package main
func main(){    lru := &lru{}    cache := initCache(lru)    cache.add("a","1")    cache.add("b","2")    cache.add("c","3")    fifo := &fifo{}    cache.setEvictionAlgo(fifo)    cache.add("d","4")    cache.setEvictionAlgo(lru)    cache.add("e","4")}

 

原文地址:https://www.cnblogs.com/gongxianjin/p/15475506.html