dongtiao6362 2013-07-22 14:00
浏览 30
已采纳

如何在Go中实现策略模式?

Here's the the general problem I am trying to solve:

  1. One set of packages is collecting data from one source and sending it to many channels.
  2. A second set of packages is collecting data from many channels and writing it to one source. This set of packages would need to translate data from multiple formats.

This seems like a perfect case for the Strategy Pattern but am not sure how best to make that work in Go.

  • 写回答

1条回答 默认 最新

  • doujia7779 2013-07-22 14:52
    关注

    In general; don't get lost in patterns and protocols to build Go applications. The language makes it easy to be expressive and straightforward. Most of the time defining solid interfaces makes everything flexible enough.

    Still, here's an example of the strategy pattern in Go:

    Define an interface for the behavior of the strategies:

    type PackageHandlingStrategy interface {
        DoThis()
        DoThat()
    }
    

    Implement that strategy:

    type SomePackageHandlingStrategy struct {
        // ...
    }
    
    func (s *SomePackageHandlingStrategy) DoThis() {
        // ...
    }
    
    func (s *SomePackageHandlingStrategy) DoThat() {
        // ...
    }
    

    And then, either embed…

    type PackageWorker struct {
        SomePackageHandlingStrategy
    }
    
    func (w *PackageWorker) Work() {
        w.DoThis()
        w.DoThat()
    }
    

    …or pass the strategy…

    type PackageWorker struct {}
    
    func (w *PackageWorker) Work(s PackageHandlingStrategy) {
        s.DoThis()
        s.DoThat()
    }
    

    … to your worker.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP