在写业务逻辑的时候如何写可扩展的代码?
之后加功能怎么不影响原来的代码?
-------------------以下是具体的应用------------------------------
//用户需要符合某些规则才能购买产品
//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