跳到主要内容

策略模式

package main

import (
"fmt"
)

//1.首先定义接口,所有的策略都是基于一套标准,这样策略(类)才有可替换性。
type IGetinfo interface {
CricleFunc(userId, tendId int) int
}

//2.接着两个接口实现类
type Hro struct {
}

func (p *Hro) CricleFunc(userId, tendId int) int {
//hro具体逻辑
return userId + tendId
}

//2.1 接口2
type Hrr struct {
}

func (p *Hrr) CricleFunc(userId, tendId int) int {
//hrr具体逻辑
return userId - tendId
}

//3.声明一个策略类

var getInfo IGetinfo

type Context struct {
A, B int
}

func (p *Context) SetContext(o IGetinfo) {
getInfo = o
}

func (p *Context) Result() int {
return getInfo.CricleFunc(p.A, p.B)
}

func main() {
//4客户端调用

c := Context{A: 15, B: 7}
// 用户自己决定使用什么策略
c.SetContext(new(Hro))
fmt.Println(c.Result())

}


package handler

import (
cs "aicloud/common/store"
"aicloud/srv/payroll/store"

"golang.org/x/net/context"
)

//1.首先定义接口,所有的策略都是基于一套标准,这样策略(类)才有可替换性。
type IPayChannel interface {
DoPay(channelId, payChargePersonName, payChargePersonIdCardType, payChargePersonIdCardId, payChargePersonMobile string) error
}

type PayChannel struct {
ctx context.Context
db *cs.DB
cycle *store.SalaryCycle
data []*store.SalaryRecord
}

func NewPayChannel() *PayChannel {
return &PayChannel{}
}

func (c *PayChannel) CreatChannelBy(channelType string) IPayChannel {
switch channelType {
case "cmb":
return &Cmb{}
case "zs":
return &Zs{}
default:
//panic("无效渠道")
return nil
}
}

//2.接着两个接口实现类
//招商银行
type Cmb struct {
ctx context.Context
db *cs.DB
cycle *store.SalaryCycle
data []*store.SalaryRecord
}

func (c *Cmb) DoPay(channelId, payChargePersonName, payChargePersonIdCardType, payChargePersonIdCardId, payChargePersonMobile string) error {
//hro具体逻辑
name := c.GetName("dd")
println(name)
return nil
}

func (c *Cmb) GetName(channelId string) string {
//cmb具体逻辑
return channelId + "fffff"
}