前端之家收集整理的这篇文章主要介绍了
golang 代码扩展,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
-------------------以下是具体的应用------------------------------
//1.在某个时间段,2.产品订单金额大于一个数
//定义结构体(规则相关的参数)
type Rule struct {
Key string
TimeStart string
TimeEnd string
OrderAmount int
}
//map关系
var muxRule map[string]func(rule *Rule) error
//定义register,有新的规则则需要调用一下这个函数进行注册
func registerBuy(key string,f func(rule *Rule) error) {
if muxRule == nil {
muxRule = make(map[string]func(rule *Rule) error)
}
if _,exist := muxRule[key]; exist {
fmt.Println("handler exist")
}
muxRule[key] = f
}
//factory,调用实际方法,返回结果
func factoryBuy(rule *Rule) error {
return muxRule[rule.Key](rule)
}
func Test_rule(t *testing.T) {
//实现规则一
rule1 := &Rule{
Key:"rule1",TimeStart:"2010-01-01 OO:00:00",TimeEnd:"2020-01-01 OO:00:00",}
opRule1 := func(rule *Rule) error {
if rule.TimeStart > time.Now().Format("2006-01-02 15:04:05") || rule.TimeEnd < time.Now().Format("2006-01-02 15:04:05") {
return errors.New("time is invalid")
}
return nil
}
//实现规则二
rule2 := &Rule{
Key:"rule2",OrderAmount:100,}
//设传入参数用户购买金额为10
amount := 10
opRule2 := func(rule *Rule) error {
if rule.OrderAmount != amount {
return errors.New("orderAmount is invalid")
}
return nil
}
registerBuy("rule1",opRule1)
registerBuy("rule2",opRule2)
ret1 := factoryBuy(rule1)
ret2 := factoryBuy(rule2)
if ret2 != nil || ret1 != nil {
fmt.Printf("ret %v\n",ret1)
fmt.Printf("ret %v\n",ret2)
}else {
fmt.Println("OK!")
}
}
输出结果:
orderAmount is invalid
原文链接:https://www.f2er.com/go/188071.html