zoukankan      html  css  js  c++  java
  • 学习Go语言之策略模式

    1.首先定义接口,所有的策略都是基于一套标准,这样策略(类)才有可替换性。声明一个计算策略接口

    1 package strategy
    2 
    3 type ICompute interface {
    4     Compute(a, b int) int
    5 }

    2.接着两个接口实现类。复习golang语言实现接口是非侵入式设计。

    1 package strategy
    2 
    3 type Add struct {
    4 }
    5 
    6 func (p *Add) Compute(a, b int) int {
    7     return a + b
    8 }
    1 package strategy
    2 
    3 type Sub struct {
    4 }
    5 
    6 func (p *Sub) Compute(a, b int) int {
    7     return a - b
    8 }

    3.声明一个策略类。复习golang中规定首字母大写是public,小写是private。如果A,B改为小写a,b,在客户端调用时会报unknown field 'a' in struct literal of type strategy.Context

     1 package strategy
     2 
     3 var compute ICompute
     4 
     5 type Context struct {
     6     A, B int
     7 }
     8 
     9 func (p *Context) SetContext(o ICompute) {
    10     compute = o
    11 }
    12 
    13 func (p *Context) Result() int {
    14     return compute.Compute(p.A, p.B)
    15 }

    4.客户端调用

     1 package main
     2 
     3 import (
     4     "fmt"
     5     "myProject/StrategyDemo/strategy"
     6 )
     7 
     8 func main() {
     9     c := strategy.Context{A: 15, B: 7}
    10     // 用户自己决定使用什么策略
    11     c.SetContext(new(strategy.Add))
    12     fmt.Println(c.Result())
    13 }

  • 相关阅读:
    EditPlus 3.7 中文版已经发布
    消息队列
    工作授权系统
    MFC学习指南大纲
    亲爱的项目经理,我恨你
    那些性感的让人尖叫的程序员
    8个经典的HTML5游戏在线试玩及源码学习
    生活小插曲
    WPF开发技术介绍
    工作总结:MFC自写排序算法(升序)
  • 原文地址:https://www.cnblogs.com/shi2310/p/11122155.html
Copyright © 2011-2022 走看看