zoukankan      html  css  js  c++  java
  • DesignPattenStrategy策略模式

    DesignPattenStrategy策略模式

    定义一系列算法,让这些算法在运行时可以互换,使得分离算法,符合开闭原则。

    UML

    • Context(环境类):负责使用算法策略,其中维持了一个抽象策略类的引用实例
    • Strategy(抽象策略类):所有策略类的父类,为所支持的策略算法声明了抽象方法,可以为接口
    • ConcreteStrategy(具体策略类):实现了在抽象策略类中声明的方法

    代码实现

    package my
    
    import "fmt"
    
    type Context struct {
       strategy Strategy
    }
    
    func NewContext(s Strategy) *Context {
       return &Context{strategy:s}
    }
    
    func (c *Context) Algorithm() {
       c.strategy.AlgorithmInterface()
    }
    
    type Strategy interface {
       AlgorithmInterface()
    }
    
    type AloOne struct {
       Name string
    }
    
    func NewAlOne(n string) *AloOne {
       return &AloOne{Name:n}
    }
    
    func (a *AloOne) AlgorithmInterface()  {
       fmt.Println("算法", a.Name)
    }
    
    type AloTwo struct {
       Name string
    }
    
    func NewAloTwo(n string) *AloTwo {
       return &AloTwo{Name:n}
    }
    
    func (a *AloTwo) AlgorithmInterface()  {
       fmt.Println("算法", a.Name)
    }
    
    // 定义工厂
    func NewStrategy(kind string) Strategy {
       switch kind {
       case "one":
          return NewAlOne(kind)
       case "two":
          return NewAloTwo(kind)
       default:
          return NewAlOne(kind)
       }
    }
    
    func TTmain() {
       strategy := NewStrategy("one")
       context := NewContext(strategy)
       context.Algorithm()
    }
    
    
    
    # 测试ttmain()输出
    算法 one
    
  • 相关阅读:
    SQL SERVER XML 学习总结
    Azkaban2官方配置文档
    I.MX6 Android CAN 命令行测试
    nginx 静态网站配置
    nginx php 配置
    uwsgi 配置 初试
    django 初试
    Ubuntu Nginx uwsgi django 初试
    I.MX6 天嵌 E9 U-boot menu hacking
    Ubuntu 搭建 LAMP 服务器
  • 原文地址:https://www.cnblogs.com/maomaomaoge/p/14126372.html
Copyright © 2011-2022 走看看