值选项模式

最后更新于:2022-04-02 02:35:39

[TOC] ## 值选项模式 > [参考](https://segmentfault.com/a/1190000013653494)
main.go ``` type IComponent interface { Mount(...IComponent) Remove(IComponent) Do(ctx context.Context) error SubDo(ctx context.Context) error } type BaseComponent struct { Components []IComponent } func (b *BaseComponent) Mount(component ...IComponent) { for _, v := range component { b.Components = append(b.Components, v) } } func (b *BaseComponent) Remove(component IComponent) { for k, v := range b.Components { if v == component { fmt.Printf("move %+v\n", reflect.TypeOf(v)) b.Components = append(b.Components[:k], b.Components[k+1:]...) } } } func (b *BaseComponent) Do(ctx context.Context) (err error) { // code return } func (b *BaseComponent) SubDo(ctx context.Context) error { for _, v := range b.Components { if err := v.Do(ctx); err != nil { return err } } return nil } type All struct { BaseComponent } func (a *All) Do(ctx context.Context) (err error) { fmt.Printf("%+v\n", runFuncName()) return a.SubDo(ctx) } type A1 struct { BaseComponent } func (a *A1) Do(ctx context.Context) (err error) { fmt.Printf("%+v\n", runFuncName()) return a.SubDo(ctx) } type A12 struct { BaseComponent } func (a *A12) Do(ctx context.Context) (err error) { fmt.Printf("%+v\n", runFuncName()) return a.SubDo(ctx) } type A11 struct { BaseComponent } func (a *A11) Do(ctx context.Context) (err error) { fmt.Printf("%+v\n", runFuncName()) return a.SubDo(ctx) } type B1 struct { BaseComponent } func (a *B1) Do(ctx context.Context) (err error) { fmt.Printf("%+v\n", runFuncName()) return a.SubDo(ctx) } type C1 struct { BaseComponent } func (a *C1) Do(ctx context.Context) (err error) { fmt.Printf("%+v\n", runFuncName()) return a.SubDo(ctx) } func main() { // 初始化订单结算页面 这个大组件 all := &All{} a1 := &A1{} a1.Mount(&A11{}, &A12{}) b1 := &B1{} all.Mount(a1, b1, &C1{}) // 只能删除本身的子组件 all.Remove(b1) // 开始构建页面组件数据 ctx := context.WithValue(context.Background(), "a", "b") all.SubDo(ctx) //output //move *main.B1 //main.(*A1).Do //main.(*A11).Do //main.(*A12).Do //main.(*C1).Do } // 获取正在运行的函数名 func runFuncName() string { pc := make([]uintptr, 1) runtime.Callers(2, pc) f := runtime.FuncForPC(pc[0]) return f.Name() } ```

';