学习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 }

原文地址:https://www.cnblogs.com/shi2310/p/11122155.html