Golang Aop之旅

AOP

===

这可能不太成熟的构想,通过struct实现AOP的简单构想

需要通过自定义的struct和context传递数据

不用反射

创建订单实例


import (

 "context"

 "errors"

 "fmt"

 "testing"

 "github.com/erDong01/micro-kit/aop"

)

type  Form  struct {
    GoodsNo  int  //商品编号
    GoodsNum int  //商品数量
}

//商品查询
type  Goods  struct {
    aop.Aop
    form Form
}

func (g *Goods) Handler() {

 if g.form.GoodsNo <= 0 {
        g.Break(errors.New("商品不存在")) //结束执行
         return
    }

    fmt.Println("商品存在")

}
// 订单处理
type  Order  struct {
    aop.Aop
    form    Form
    OrderNo int
    Status  int8
}

func (o *Order) Handler() {

 o.OrderNo = 123456

 o.Status = 1

    fmt.Println("创建订单")

}

func (o *Order) After() {

    o.Set("order_no", o.OrderNo)

}
//支付处理
type  Pay  struct {
    aop.Aop
    OrderNo int
}

func (p *Pay) Before() {
     p.OrderNo = p.Get("order_no").(int)
}

func (p *Pay) Handler() {

    fmt.Println("为订单号:", p.OrderNo, "创建支付订单")

}

// 库存处理
type  Stock  struct {
    aop.Aop
    form Form
}

func (s *Stock) Handler() {

    fmt.Println("减去库存数量:", s.form.GoodsNum)

}

func  TestOrder(t *testing.T) {

     form := Form{GoodsNo: 11, GoodsNum: 1}

    aop.New(context.Background(), &Order{form: form,}).SetBefore(&Goods{

        form: form,

    }).SetAfter(&Pay{}, &Stock{form: form}).Run()

}

大家有什么好的想法请留言

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!