学习Go语言之简单工厂模式

1.首先定义接口

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

2.接着两个接口实现类。

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.声明一个工厂类

 1 package strategy
 2 
 3 // 用户自己希望工厂产出
 4 func Factory(s string) ICompute {
 5     var computer ICompute
 6     switch s {
 7     case "+":
 8         computer = new(Add)
 9         break
10     case "-":
11         computer = new(Sub)
12         break
13     }
14     return computer
15 }

4.客户端调用

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "myProject/strategy"
 6 )
 7 
 8 func main() {
 9     c := strategy.Factory("-")
10     fmt.Println(c.Compute(15, 8))
11 }

 

posted @ 2019-08-26 16:24  卓扬  阅读(389)  评论(0编辑  收藏  举报