并发组件 | Go设计模式实战

GoLang设计模式20 - 组合模式 Python微信订餐小程序课程视频 https://edu.youkuaiyun.com/course/detail/36074 Python实战量化交易理财系统 https://edu.youkuaiyun.com/course/detail/35475 定义 组合模式是一种结构型设计模式。 当我们想把一组对象当做一个整体来处理时就可以考虑使用组合模式。 组合模式被视为是接口型设计模式是因为它将一组对象组装为一个树状结构。这个树状结构中的每个独立组件都可以用同样的方式来处理——无论它们是复杂的还是原始的。 以计算机操作系统中的文 阅读详情

嗯,Go设计模式实战系列,一个设计模式业务真实使用的golang系列。

前言

本系列主要分享,如何在我们的真实业务场景中使用设计模式。

本系列文章主要采用如下结构:

  • 什么是「XX设计模式」?

  • 什么真实业务场景可以使用「XX设计模式」?

  • 怎么用「XX设计模式」?

本文主要介绍「组合模式」结合Go语言天生的并发特性,如何在真实业务场景中使用。

之前文章《代码组件 | Go设计模式实战》已经介绍了「组合模式」的概念,以及在业务中的使用。今天我们结合Go语言天生的并发特性,升级「组合模式」为「并发组合模式」。

我们先来简单回顾下「组合模式」的知识,详细可以查看上篇文章《代码组件 | Go设计模式实战》

什么是「并发组合模式」?

组合模式的概念:

一个具有层级关系的对象由一系列拥有父子关系的对象通过树形结构组成。

并发组合模式的概念:

一个具有层级关系的对象由一系列拥有父子关系的对象通过树形结构组成,子对象即可被串行执行,也可被并发执行

并发组合模式的优势:

  • 原本串行的业务(存在阻塞的部分,比如网络IO等)可以被并发执行,利用多核优势提升性能。

什么真实业务场景可以用「并发组合模式」?

我们还是以「组合模式」中的“订单结算页面”为例,继续来看看某东的订单结算页面:

从页面的展示形式上,可以看出:

  • 页面由多个模块构成,比如:

    • 地址模块:获取用户地址数据

    • 支付方式模块:获取支付方式列表

    • 店铺模块:获取店铺、购物车选中商品等信息

    • 发票模块:获取发票类型列表

    • 优惠券模块:获取用户优惠券列表

    • 某豆模块:获取用户积分信息

    • 礼品卡模块:获取礼品卡列表列表

    • 订单详细金额模块:获取订单金额信息

  • 单个模块可以由多个子模块构成

    • 商品模块:获取购物车选中商品信息

    • 售后模块:获取商品售后信息

    • 优惠模块:获取商品参与的优惠活动信息

    • 物流模块:获取商品支持的配送方式列表

    • 店铺模块,又由如下模块构成:

按照「组合模式」的业务逻辑执行流程:

但是,我们很清楚有些模块之间并没有依赖,且该模块涉及服务远程调用等阻塞操作,比如:

  • 地址模块调用地址服务获取用户地址数据时。

  • 支付方式模块也可以同时去读redis获取支付方式列表数据等等。

所以: 有的模块其实可以被并发的执行。

如果把上面不存在依赖关系的模块修改为并发的执行,则我们得到如下的执行流程:

怎么用「并发组合模式」?

关于「并发组合模式」的建模过程完全可以参考之前文章《代码组件 | Go设计模式实战》,我们这里只说说需要着重注意的地方。

「并发组合模式」的核心还是Component组件接口,我们先看看「组合模式」的Component组件接口如下(再之前的文章上做了优化,进一步封装提取了BusinessLogicDo方法):

// Component 组件接口
type Component interface {
	// 添加一个子组件
	Mount(c Component, components ...Component) error
	// 移除一个子组件
	Remove(c Component) error
	// 执行当前组件业务和执行子组件
	// ctx 业务上下文
	// currentConponent 当前组件
	Do(ctx *Context, currentConponent Component) error
	// 执行当前组件业务业务逻辑
	BusinessLogicDo(ctx *Context) error
	// 执行子组件
	ChildsDo(ctx *Context) error
}

再来看看「并发组合模式」的Component`组件接口,如下(重点看和「组合模式」的区别):

// Component 组件接口
type Component interface {
	// 添加一个子组件
	Mount(c Component, components ...Component) error
	// 移除一个子组件
	Remove(c Component) error
	// 执行当前组件业务:`BusinessLogicDo`和执行子组件:`ChildsDo`
	// ctx 业务上下文
	// currentConponent 当前组件
	// wg 父组件的WaitGroup对象
	// 区别1:增加了WaitGroup对象参数,目的是等待并发子组件的执行完成。
	Do(ctx *Context, currentConponent Component, wg *sync.WaitGroup) error
	// 执行当前组件业务逻辑
	// resChan 回写当前组件业务执行结果的channel
	// 区别2:增加了一个channel参数,目的是并发组件执行逻辑时引入了超时机制,需要一个channel接受组件的执行结果
	BusinessLogicDo(resChan chan interface{}) error
	// 执行子组件
	ChildsDo(ctx *Context) error
}

我们详细再来看,相对于「组合模式」,引入并发之后需要着重关注如下几点:

  • 并发子组件需要设置超时时间:防止子组件执行时间过长,解决方案关键字context.WithTimeout

  • 区分普通组件和并发组件:合成复用基础组件,封装为并发基础组件

  • 拥有并发子组件的父组件需要等待并发子组件执行完毕(包含超时),解决方案关键字sync.WaitGroup

  • 并发子组件执行自身业务逻辑是需检测超时:防止子组件内部执行业务逻辑时间过长,解决方案关键字select和<-ctx.Done()

第一点:并发子组件需要设置超时时间

// Context 业务上下文
type Context struct {
	// context.WithTimeout派生的子上下文
	TimeoutCtx context.Context
	// 超时函数
	context.CancelFunc
}

第二点:区分普通组件和并发组件

增加新的并发基础组件结构体BaseConcurrencyComponent,并合成复用「组合模式」中的基础组件BaseComponent,如下:

// BaseConcurrencyComponent 并发基础组件
type BaseConcurrencyComponent struct {
	// 合成复用基础组件
	BaseComponent
	// 当前组件是否有并发子组件
	HasChildConcurrencyComponents bool
	// 并发子组件列表
	ChildConcurrencyComponents []Component
	// wg 对象
	*sync.WaitGroup
	// 当前组件业务执行结果channel
	logicResChan chan interface{}
	// 当前组件执行过程中的错误信息
	Err error
}

第三点:拥有并发子组件的父组件需要等待并发子组件执行完毕(包含超时)

修改「组合模式」中的ChildsDo方法,使其支持并发执行子组件,主要修改和实现如下:

  • 通过go关键字执行子组件

  • 通过*WaitGroup.Wait()等待子组件执行结果

// ChildsDo 执行子组件
func (bc *BaseConcurrencyComponent) ChildsDo(ctx *Context) (err error) {
	if bc.WaitGroup == nil {
		bc.WaitGroup = &sync.WaitGroup{}
	}
	// 执行并发子组件
	for _, childComponent := range bc.ChildConcurrencyComponents {
		bc.WaitGroup.Add(1)
		go childComponent.Do(ctx, childComponent, bc.WaitGroup)
	}
	// 执行子组件
	for _, childComponent := range bc.ChildComponents {
		if err = childComponent.Do(ctx, childComponent, nil); err != nil {
			return err
		}
	}
	if bc.HasChildConcurrencyComponents {
		// 等待并发组件执行结果
		bc.WaitGroup.Wait()
	}
	return
}

第四点:并发子组件执行自身业务逻辑是需检测超时

select关键字context.WithTimeout()派生的子上下文Done()方案返回的channel,发生超时该channel会被关闭。具体实现代码如下:

// Do 执行子组件
// ctx 业务上下文
// currentConponent 当前组件
// wg 父组件的waitgroup对象
func (bc *BaseConcurrencyComponent) Do(ctx *Context, currentConponent Component, wg *sync.WaitGroup) (err error) {
	defer wg.Done()
	// 初始化并发子组件channel
	if bc.logicResChan == nil {
		bc.logicResChan = make(chan interface{}, 1)
	}

	go currentConponent.BusinessLogicDo(bc.logicResChan)

	select {
	// 等待业务执行结果
	case <-bc.logicResChan:
		// 业务执行结果
		fmt.Println(runFuncName(), "bc.BusinessLogicDo wait.done...")
		break
	// 超时等待
	case <-ctx.TimeoutCtx.Done():
		// 超时退出
		fmt.Println(runFuncName(), "bc.BusinessLogicDo timeout...")
		bc.Err = ErrConcurrencyComponentTimeout
		break
	}
	// 执行子组件
	err = currentConponent.ChildsDo(ctx)
	return
}

代码demo
package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"reflect"
	"sync"
	"time"
)

//------------------------------------------------------------
//Go设计模式实战系列
//组合模式
//@auhtor TIGERB<https://github.com/TIGERB>
//------------------------------------------------------------

//example:
// 创建一个根组件
// 如果子组件存在并发组件则父组件必须为并发组件
// type RootComponent struct {
// 	BaseConcurrencyComponent
// }
//
// func (bc *RootComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
// 	// do nothing
// 	return
// }
//
// 创建一个并发组件
// type DemoConcurrenyComponent struct {
// 	BaseConcurrencyComponent
// }
//
// func (bc *DemoConcurrenyComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
// 	// 并发组件业务逻辑填充到这
// 	return
// }
//
// 创建一个普通组件
// type DemoComponent struct {
// 	BaseComponent
// }
//
// func (bc *DemoComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
// 	// 普通组件业务逻辑填充到这
// 	return
// }
//
// // 普通组件
// root.Mount(
// 	&DemoComponent{},
// )
//
// // 并发组件
// root := &RootComponent{}
// root.MountConcurrency(
// 	&DemoConcurrenyComponent{},
// )
//
// // 初始化业务上下文 并设置超时时间
// ctx := GetContext(5 * time.Second)
// defer ctx.CancelFunc()
// // 开始执行子组件
// root.ChildsDo(ctx)

var (
	// ErrConcurrencyComponentTimeout 并发组件业务超时
	ErrConcurrencyComponentTimeout = errors.New("Concurrency Component Timeout")
)

// Context 业务上下文
type Context struct {
	// context.WithTimeout派生的子上下文
	TimeoutCtx context.Context
	// 超时函数
	context.CancelFunc
}

// GetContext 获取业务上下文实例
// d 超时时间
func GetContext(d time.Duration) *Context {
	c := &Context{}
	c.TimeoutCtx, c.CancelFunc = context.WithTimeout(context.Background(), d)
	return c
}

// Component 组件接口
type Component interface {
	// 添加一个子组件
	Mount(c Component, components ...Component) error
	// 移除一个子组件
	Remove(c Component) error
	// 执行当前组件业务:`BusinessLogicDo`和执行子组件:`ChildsDo`
	// ctx 业务上下文
	// currentConponent 当前组件
	// wg 父组件的waitgroup对象
	Do(ctx *Context, currentConponent Component, wg *sync.WaitGroup) error
	// 执行当前组件业务逻辑
	// resChan 回写当前组件业务执行结果的channel
	BusinessLogicDo(resChan chan interface{}) error
	// 执行子组件
	ChildsDo(ctx *Context) error
}

// BaseComponent 基础组件
// 实现Add:添加一个子组件
// 实现Remove:移除一个子组件
type BaseComponent struct {
	// 子组件列表
	ChildComponents []Component
}

// Mount 挂载一个子组件
func (bc *BaseComponent) Mount(c Component, components ...Component) (err error) {
	bc.ChildComponents = append(bc.ChildComponents, c)
	if len(components) == 0 {
		return
	}
	bc.ChildComponents = append(bc.ChildComponents, components...)
	return
}

// Remove 移除一个子组件
func (bc *BaseComponent) Remove(c Component) (err error) {
	if len(bc.ChildComponents) == 0 {
		return
	}
	for k, childComponent := range bc.ChildComponents {
		if c == childComponent {
			fmt.Println(runFuncName(), "移除:", reflect.TypeOf(childComponent))
			bc.ChildComponents = append(bc.ChildComponents[:k], bc.ChildComponents[k+1:]...)
		}
	}
	return
}

// Do 执行子组件
// ctx 业务上下文
// currentConponent 当前组件
// wg 父组件的waitgroup对象
func (bc *BaseComponent) Do(ctx *Context, currentConponent Component, wg *sync.WaitGroup) (err error) {
	//执行当前组件业务代码
	err = currentConponent.BusinessLogicDo(nil)
	if err != nil {
		return err
	}
	// 执行子组件
	return currentConponent.ChildsDo(ctx)
}

// BusinessLogicDo 当前组件业务逻辑代码填充处
func (bc *BaseComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
	// do nothing
	return
}

// ChildsDo 执行子组件
func (bc *BaseComponent) ChildsDo(ctx *Context) (err error) {
	// 执行子组件
	for _, childComponent := range bc.ChildComponents {
		if err = childComponent.Do(ctx, childComponent, nil); err != nil {
			return err
		}
	}
	return
}

// BaseConcurrencyComponent 并发基础组件
type BaseConcurrencyComponent struct {
	// 合成复用基础组件
	BaseComponent
	// 当前组件是否有并发子组件
	HasChildConcurrencyComponents bool
	// 并发子组件列表
	ChildConcurrencyComponents []Component
	// wg 对象
	*sync.WaitGroup
	// 当前组件业务执行结果channel
	logicResChan chan interface{}
	// 当前组件执行过程中的错误信息
	Err error
}

// Remove 移除一个子组件
func (bc *BaseConcurrencyComponent) Remove(c Component) (err error) {
	if len(bc.ChildComponents) == 0 {
		return
	}
	for k, childComponent := range bc.ChildComponents {
		if c == childComponent {
			fmt.Println(runFuncName(), "移除:", reflect.TypeOf(childComponent))
			bc.ChildComponents = append(bc.ChildComponents[:k], bc.ChildComponents[k+1:]...)
		}
	}
	for k, childComponent := range bc.ChildConcurrencyComponents {
		if c == childComponent {
			fmt.Println(runFuncName(), "移除:", reflect.TypeOf(childComponent))
			bc.ChildConcurrencyComponents = append(bc.ChildComponents[:k], bc.ChildComponents[k+1:]...)
		}
	}
	return
}

// MountConcurrency 挂载一个并发子组件
func (bc *BaseConcurrencyComponent) MountConcurrency(c Component, components ...Component) (err error) {
	bc.HasChildConcurrencyComponents = true
	bc.ChildConcurrencyComponents = append(bc.ChildConcurrencyComponents, c)
	if len(components) == 0 {
		return
	}
	bc.ChildConcurrencyComponents = append(bc.ChildConcurrencyComponents, components...)
	return
}

// ChildsDo 执行子组件
func (bc *BaseConcurrencyComponent) ChildsDo(ctx *Context) (err error) {
	if bc.WaitGroup == nil {
		bc.WaitGroup = &sync.WaitGroup{}
	}
	// 执行并发子组件
	for _, childComponent := range bc.ChildConcurrencyComponents {
		bc.WaitGroup.Add(1)
		go childComponent.Do(ctx, childComponent, bc.WaitGroup)
	}
	// 执行子组件
	for _, childComponent := range bc.ChildComponents {
		if err = childComponent.Do(ctx, childComponent, nil); err != nil {
			return err
		}
	}
	if bc.HasChildConcurrencyComponents {
		// 等待并发组件执行结果
		bc.WaitGroup.Wait()
	}
	return
}

// Do 执行子组件
// ctx 业务上下文
// currentConponent 当前组件
// wg 父组件的waitgroup对象
func (bc *BaseConcurrencyComponent) Do(ctx *Context, currentConponent Component, wg *sync.WaitGroup) (err error) {
	defer wg.Done()
	// 初始化并发子组件channel
	if bc.logicResChan == nil {
		bc.logicResChan = make(chan interface{}, 1)
	}

	go currentConponent.BusinessLogicDo(bc.logicResChan)

	select {
	// 等待业务执行结果
	case <-bc.logicResChan:
		// 业务执行结果
		fmt.Println(runFuncName(), "bc.BusinessLogicDo wait.done...")
		break
	// 超时等待
	case <-ctx.TimeoutCtx.Done():
		// 超时退出
		fmt.Println(runFuncName(), "bc.BusinessLogicDo timeout...")
		bc.Err = ErrConcurrencyComponentTimeout
		break
	}
	// 执行子组件
	err = currentConponent.ChildsDo(ctx)
	return
}

// CheckoutPageComponent 订单结算页面组件
type CheckoutPageComponent struct {
	// 合成复用基础组件
	BaseConcurrencyComponent
}

// BusinessLogicDo 当前组件业务逻辑代码填充处
func (bc *CheckoutPageComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
	// 当前组件的业务逻辑写这
	fmt.Println(runFuncName(), "订单结算页面组件...")
	return
}

// AddressComponent 地址组件
type AddressComponent struct {
	// 合成复用基础组件
	BaseConcurrencyComponent
}

// BusinessLogicDo 并发组件实际填充业务逻辑的地方
func (bc *AddressComponent) BusinessLogicDo(resChan chan interface{}) error {
	fmt.Println(runFuncName(), "地址组件...")
	fmt.Println(runFuncName(), "获取地址信息 ing...")

	// 模拟远程调用地址服务
	http.Get("http://example.com/")

	resChan <- struct{}{} // 写入业务执行结果
	fmt.Println(runFuncName(), "获取地址信息 done...")
	return nil
}

// PayMethodComponent 支付方式组件
type PayMethodComponent struct {
	// 合成复用基础组件
	BaseConcurrencyComponent
}

// BusinessLogicDo 并发组件实际填充业务逻辑的地方
func (bc *PayMethodComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
	// 当前组件的业务逻辑写这
	fmt.Println(runFuncName(), "支付方式组件...")
	fmt.Println(runFuncName(), "获取支付方式 ing...")
	// 模拟远程调用地址服务 略
	resChan <- struct{}{}
	fmt.Println(runFuncName(), "获取支付方式 done...")
	return nil
}

// StoreComponent 店铺组件
type StoreComponent struct {
	// 合成复用基础组件
	BaseComponent
}

// BusinessLogicDo 并发组件实际填充业务逻辑的地方
func (bc *StoreComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
	// 当前组件的业务逻辑写这
	fmt.Println(runFuncName(), "店铺组件...")
	return
}

// SkuComponent 商品组件
type SkuComponent struct {
	// 合成复用基础组件
	BaseComponent
}

// BusinessLogicDo 并发组件实际填充业务逻辑的地方
func (bc *SkuComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
	// 当前组件的业务逻辑写这
	fmt.Println(runFuncName(), "商品组件...")
	return
}

// PromotionComponent 优惠信息组件
type PromotionComponent struct {
	// 合成复用基础组件
	BaseComponent
}

// BusinessLogicDo 并发组件实际填充业务逻辑的地方
func (bc *PromotionComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
	// 当前组件的业务逻辑写这
	fmt.Println(runFuncName(), "优惠信息组件...")
	return
}

// ExpressComponent 物流组件
type ExpressComponent struct {
	// 合成复用基础组件
	BaseComponent
}

// BusinessLogicDo 并发组件实际填充业务逻辑的地方
func (bc *ExpressComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
	// 当前组件的业务逻辑写这
	fmt.Println(runFuncName(), "物流组件...")
	return
}

// AftersaleComponent 售后组件
type AftersaleComponent struct {
	// 合成复用基础组件
	BaseComponent
}

// BusinessLogicDo 并发组件实际填充业务逻辑的地方
func (bc *AftersaleComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
	// 当前组件的业务逻辑写这
	fmt.Println(runFuncName(), "售后组件...")
	return
}

// InvoiceComponent 发票组件
type InvoiceComponent struct {
	// 合成复用基础组件
	BaseConcurrencyComponent
}

// BusinessLogicDo 并发组件实际填充业务逻辑的地方
func (bc *InvoiceComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
	// 当前组件的业务逻辑写这
	fmt.Println(runFuncName(), "发票组件...")
	fmt.Println(runFuncName(), "获取发票信息 ing...")
	// 模拟远程调用地址服务 略
	resChan <- struct{}{} // 写入业务执行结果
	fmt.Println(runFuncName(), "获取发票信息 done...")
	return
}

// CouponComponent 优惠券组件
type CouponComponent struct {
	// 合成复用基础组件
	BaseConcurrencyComponent
}

// BusinessLogicDo 并发组件实际填充业务逻辑的地方
func (bc *CouponComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
	// 当前组件的业务逻辑写这
	fmt.Println(runFuncName(), "优惠券组件...")
	fmt.Println(runFuncName(), "获取最优优惠券 ing...")

	// 模拟远程调用优惠券服务
	http.Get("http://example.com/")

	// 写入业务执行结果
	resChan <- struct{}{}
	fmt.Println(runFuncName(), "获取最优优惠券 done...")
	return
}

// GiftCardComponent 礼品卡组件
type GiftCardComponent struct {
	// 合成复用基础组件
	BaseConcurrencyComponent
}

// BusinessLogicDo 并发组件实际填充业务逻辑的地方
func (bc *GiftCardComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
	// 当前组件的业务逻辑写这
	fmt.Println(runFuncName(), "礼品卡组件...")
	fmt.Println(runFuncName(), "获取礼品卡信息 ing...")
	// 模拟远程调用地址服务 略
	resChan <- struct{}{} // 写入业务执行结果
	fmt.Println(runFuncName(), "获取礼品卡信息 done...")
	return
}

// OrderComponent 订单金额详细信息组件
type OrderComponent struct {
	// 合成复用基础组件
	BaseComponent
}

// BusinessLogicDo 当前组件业务逻辑代码填充处
func (bc *OrderComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
	// 当前组件的业务逻辑写这
	fmt.Println(runFuncName(), "订单金额详细信息组件...")
	return
}

// Demo 示例
func Demo() {
	// 初始化订单结算页面 这个大组件
	checkoutPage := &CheckoutPageComponent{}

	// 挂载子组件
	storeComponent := &StoreComponent{}
	skuComponent := &SkuComponent{}
	skuComponent.Mount(
		&PromotionComponent{},
		&AftersaleComponent{},
	)
	storeComponent.Mount(
		skuComponent,
		&ExpressComponent{},
	)

	// ---挂载组件---

	// 普通组件
	checkoutPage.Mount(
		storeComponent,
		&OrderComponent{},
	)
	// 并发组件
	checkoutPage.MountConcurrency(
		&AddressComponent{},
		&PayMethodComponent{},
		&InvoiceComponent{},
		&CouponComponent{},
		&GiftCardComponent{},
	)

	// 初始化业务上下文 并设置超时时间
	ctx := GetContext(5 * time.Second)
	defer ctx.CancelFunc()
	// 开始构建页面组件数据
	checkoutPage.ChildsDo(ctx)
}

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU() - 1)
	Demo()
}

// 获取正在运行的函数名
func runFuncName() string {
	pc := make([]uintptr, 1)
	runtime.Callers(2, pc)
	f := runtime.FuncForPC(pc[0])
	return f.Name()
	return ""
}



代码运行结果:

Running] go run "../easy-tips/go/patterns/composite/concurrency/composite-concurrency.go"
main.(*StoreComponent).BusinessLogicDo 店铺组件...
main.(*SkuComponent).BusinessLogicDo 商品组件...
main.(*PromotionComponent).BusinessLogicDo 优惠信息组件...
main.(*AftersaleComponent).BusinessLogicDo 售后组件...
main.(*ExpressComponent).BusinessLogicDo 物流组件...
main.(*OrderComponent).BusinessLogicDo 订单金额详细信息组件...
main.(*PayMethodComponent).BusinessLogicDo 支付方式组件...
main.(*PayMethodComponent).BusinessLogicDo 获取支付方式 ing...
main.(*InvoiceComponent).BusinessLogicDo 发票组件...
main.(*InvoiceComponent).BusinessLogicDo 获取发票信息 ing...
main.(*GiftCardComponent).BusinessLogicDo 礼品卡组件...
main.(*GiftCardComponent).BusinessLogicDo 获取礼品卡信息 ing...
main.(*CouponComponent).BusinessLogicDo 优惠券组件...
main.(*CouponComponent).BusinessLogicDo 获取发票信息 ing...
main.(*AddressComponent).BusinessLogicDo 地址组件...
main.(*AddressComponent).BusinessLogicDo 获取地址信息 ing...
main.(*InvoiceComponent).BusinessLogicDo 获取发票信息 done...
main.(*BaseConcurrencyComponent).Do bc.BusinessLogicDo wait.done...
main.(*BaseConcurrencyComponent).Do bc.BusinessLogicDo wait.done...
main.(*PayMethodComponent).BusinessLogicDo 获取支付方式 done...
main.(*AddressComponent).BusinessLogicDo 获取地址信息 done...
main.(*BaseConcurrencyComponent).Do bc.BusinessLogicDo wait.done...
main.(*CouponComponent).BusinessLogicDo 获取发票信息 done...
main.(*BaseConcurrencyComponent).Do bc.BusinessLogicDo wait.done...
main.(*GiftCardComponent).BusinessLogicDo 获取礼品卡信息 done...
main.(*BaseConcurrencyComponent).Do bc.BusinessLogicDo wait.done...

「组合模式」和「并发组合模式」基准测试对比

基准测试代码:

package composite

import (
	"easy-tips/go/patterns/composite/concurrency"
	"easy-tips/go/patterns/composite/normal"
	"runtime"
	"testing"
)

// go test -benchmem -run=^$ easy-tips/go/patterns/composite -bench . -v -count=1 --benchtime 20s

func Benchmark_Normal(b *testing.B) {
	b.SetParallelism(runtime.NumCPU())
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			normal.Demo()
		}
	})
}

func Benchmark_Concurrency(b *testing.B) {
	b.SetParallelism(runtime.NumCPU())
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			concurrency.Demo()
		}
	})
}

本地机器Benchmark对比测试结果:

(TIGERB) ???? ➜  composite git:(master) ✗ go test -benchmem -run=^$ easy-tips/go/patterns/composite -bench . -v -count=1 --benchtime 20s 
goos: darwin
goarch: amd64
pkg: easy-tips/go/patterns/composite
Benchmark_Normal-4                   376          56666895 ns/op           35339 B/op        286 allocs/op
Benchmark_Concurrency-4              715          32669301 ns/op           36445 B/op        299 allocs/op
PASS
ok      easy-tips/go/patterns/composite 68.835s

从上面的基准测试结果可以看出来Benchmark_Concurrency-4平均每次的执行时间是32669301 ns是要优于Benchmark_Normal的56666895 ns。

结语

「并发组合模式」是一个由特定的设计模式结合Go语言天生的并发特性,通过适当封装形成的“新模式”。

附录「并发组合模式」的基础代码模板与使用说明

//------------------------------------------------------------
//Go设计模式实战系列
//组合模式
//@auhtor TIGERB<https://github.com/TIGERB>
//------------------------------------------------------------

//example:
// 创建一个根组件
// 如果子组件存在并发组件则父组件必须为并发组件
// type RootComponent struct {
// 	BaseConcurrencyComponent
// }
//
// func (bc *RootComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
// 	// do nothing
// 	return
// }
//
// 创建一个并发组件
// type DemoConcurrenyComponent struct {
// 	BaseConcurrencyComponent
// }
//
// func (bc *DemoConcurrenyComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
// 	// 并发组件业务逻辑填充到这
// 	return
// }
//
// 创建一个普通组件
// type DemoComponent struct {
// 	BaseComponent
// }
//
// func (bc *DemoComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
// 	// 普通组件业务逻辑填充到这
// 	return
// }
//
// // 普通组件
// root.Mount(
// 	&DemoComponent{},
// )
//
// // 并发组件
// root := &RootComponent{}
// root.MountConcurrency(
// 	&DemoConcurrenyComponent{},
// )
//
// // 初始化业务上下文 并设置超时时间
// ctx := GetContext(5 * time.Second)
// defer ctx.CancelFunc()
// // 开始执行子组件
// root.ChildsDo(ctx)

var (
	// ErrConcurrencyComponentTimeout 并发组件业务超时
	ErrConcurrencyComponentTimeout = errors.New("Concurrency Component Timeout")
)

// Context 业务上下文
type Context struct {
	// context.WithTimeout派生的子上下文
	TimeoutCtx context.Context
	// 超时函数
	context.CancelFunc
}

// GetContext 获取业务上下文实例
// d 超时时间
func GetContext(d time.Duration) *Context {
	c := &Context{}
	c.TimeoutCtx, c.CancelFunc = context.WithTimeout(context.Background(), d)
	return c
}

// Component 组件接口
type Component interface {
	// 添加一个子组件
	Mount(c Component, components ...Component) error
	// 移除一个子组件
	Remove(c Component) error
	// 执行当前组件业务:`BusinessLogicDo`和执行子组件:`ChildsDo`
	// ctx 业务上下文
	// currentConponent 当前组件
	// wg 父组件的waitgroup对象
	Do(ctx *Context, currentConponent Component, wg *sync.WaitGroup) error
	// 执行当前组件业务逻辑
	// resChan 回写当前组件业务执行结果的channel
	BusinessLogicDo(resChan chan interface{}) error
	// 执行子组件
	ChildsDo(ctx *Context) error
}

// BaseComponent 基础组件
// 实现Add:添加一个子组件
// 实现Remove:移除一个子组件
type BaseComponent struct {
	// 子组件列表
	ChildComponents []Component
}

// Mount 挂载一个子组件
func (bc *BaseComponent) Mount(c Component, components ...Component) (err error) {
	bc.ChildComponents = append(bc.ChildComponents, c)
	if len(components) == 0 {
		return
	}
	bc.ChildComponents = append(bc.ChildComponents, components...)
	return
}

// Remove 移除一个子组件
func (bc *BaseComponent) Remove(c Component) (err error) {
	if len(bc.ChildComponents) == 0 {
		return
	}
	for k, childComponent := range bc.ChildComponents {
		if c == childComponent {
			fmt.Println(runFuncName(), "移除:", reflect.TypeOf(childComponent))
			bc.ChildComponents = append(bc.ChildComponents[:k], bc.ChildComponents[k+1:]...)
		}
	}
	return
}

// Do 执行子组件
// ctx 业务上下文
// currentConponent 当前组件
// wg 父组件的waitgroup对象
func (bc *BaseComponent) Do(ctx *Context, currentConponent Component, wg *sync.WaitGroup) (err error) {
	//执行当前组件业务代码
	err = currentConponent.BusinessLogicDo(nil)
	if err != nil {
		return err
	}
	// 执行子组件
	return currentConponent.ChildsDo(ctx)
}

// BusinessLogicDo 当前组件业务逻辑代码填充处
func (bc *BaseComponent) BusinessLogicDo(resChan chan interface{}) (err error) {
	// do nothing
	return
}

// ChildsDo 执行子组件
func (bc *BaseComponent) ChildsDo(ctx *Context) (err error) {
	// 执行子组件
	for _, childComponent := range bc.ChildComponents {
		if err = childComponent.Do(ctx, childComponent, nil); err != nil {
			return err
		}
	}
	return
}

// BaseConcurrencyComponent 并发基础组件
type BaseConcurrencyComponent struct {
	// 合成复用基础组件
	BaseComponent
	// 当前组件是否有并发子组件
	HasChildConcurrencyComponents bool
	// 并发子组件列表
	ChildConcurrencyComponents []Component
	// wg 对象
	*sync.WaitGroup
	// 当前组件业务执行结果channel
	logicResChan chan interface{}
	// 当前组件执行过程中的错误信息
	Err error
}

// Remove 移除一个子组件
func (bc *BaseConcurrencyComponent) Remove(c Component) (err error) {
	if len(bc.ChildComponents) == 0 {
		return
	}
	for k, childComponent := range bc.ChildComponents {
		if c == childComponent {
			fmt.Println(runFuncName(), "移除:", reflect.TypeOf(childComponent))
			bc.ChildComponents = append(bc.ChildComponents[:k], bc.ChildComponents[k+1:]...)
		}
	}
	for k, childComponent := range bc.ChildConcurrencyComponents {
		if c == childComponent {
			fmt.Println(runFuncName(), "移除:", reflect.TypeOf(childComponent))
			bc.ChildConcurrencyComponents = append(bc.ChildComponents[:k], bc.ChildComponents[k+1:]...)
		}
	}
	return
}

// MountConcurrency 挂载一个并发子组件
func (bc *BaseConcurrencyComponent) MountConcurrency(c Component, components ...Component) (err error) {
	bc.HasChildConcurrencyComponents = true
	bc.ChildConcurrencyComponents = append(bc.ChildConcurrencyComponents, c)
	if len(components) == 0 {
		return
	}
	bc.ChildConcurrencyComponents = append(bc.ChildConcurrencyComponents, components...)
	return
}

// ChildsDo 执行子组件
func (bc *BaseConcurrencyComponent) ChildsDo(ctx *Context) (err error) {
	if bc.WaitGroup == nil {
		bc.WaitGroup = &sync.WaitGroup{}
	}
	// 执行并发子组件
	for _, childComponent := range bc.ChildConcurrencyComponents {
		bc.WaitGroup.Add(1)
		go childComponent.Do(ctx, childComponent, bc.WaitGroup)
	}
	// 执行子组件
	for _, childComponent := range bc.ChildComponents {
		if err = childComponent.Do(ctx, childComponent, nil); err != nil {
			return err
		}
	}
	if bc.HasChildConcurrencyComponents {
		// 等待并发组件执行结果
		bc.WaitGroup.Wait()
	}
	return
}

// Do 执行子组件
// ctx 业务上下文
// currentConponent 当前组件
// wg 父组件的waitgroup对象
func (bc *BaseConcurrencyComponent) Do(ctx *Context, currentConponent Component, wg *sync.WaitGroup) (err error) {
	defer wg.Done()
	// 初始化并发子组件channel
	if bc.logicResChan == nil {
		bc.logicResChan = make(chan interface{}, 1)
	}

	go currentConponent.BusinessLogicDo(bc.logicResChan)

	select {
	// 等待业务执行结果
	case <-bc.logicResChan:
		// 业务执行结果
		fmt.Println(runFuncName(), "bc.BusinessLogicDo wait.done...")
		break
	// 超时等待
	case <-ctx.TimeoutCtx.Done():
		// 超时退出
		fmt.Println(runFuncName(), "bc.BusinessLogicDo timeout...")
		bc.Err = ErrConcurrencyComponentTimeout
		break
	}
	// 执行子组件
	err = currentConponent.ChildsDo(ctx)
	return
}

特别说明:
本系列的一些设计模式的概念可能和原概念存在差异,因为会结合实际使用,取其精华,适当改变,灵活使用。

Go设计模式实战系列 更多文章

Golang高并发编程指南:如何避免常见的并发陷阱 本文旨在为Golang开发者提供全面的高并发编程指南,重点解决在实际开发中遇到的并发问题。内容涵盖从基础概念到高级技巧的全方位知识,特别关注如何识别和避免常见的并发陷阱。文章首先介绍Golang并发模型的核心概念,然后深入分析各种并发陷阱及其解决方案,接着通过实际案例展示最佳实践,最后讨论性能优化和未来发展趋势。goroutine: Golang中的轻量级线程,由Go运行时管理channel: Golang提供的用于goroutine间通信的管道竞态条件(Race Condition) 阅读详情

相关推荐

ECS:基于Go语言的实体组件系统实施

ECS(Entity-Component-System)设计模式是一种面向数据驱动架构的游戏开发方法,它将游戏世界中的对象分解为三个主要部分:实体(Entity)、组件(Component)和系统(System)。实体作为对象的标识,不直接拥有数据,而是由组件来描述其特征。组件作为纯数据容器,实现数据的共享和重用。系统则负责处理游戏逻辑,通过组件数据进行操作。在本章中,我们将简要探索ECS的基本概念,了解其设计原则,以及如何利用ECS模式来组织和优化游戏代码结构,从而提升开发效率和游戏性能。

weixin_36369848的博客 1013

golang 并发

并发 Go语言的并发通过goroutine`实现。goroutine类似于线程,属于用户态的线程,我们可以根据需要创建成千上万个goroutine并发工作。goroutine是由Go语言的运行时(runtime)调度完成,而线程是由操作系统调度完成。 Go语言还提供channel在多个goroutine间进行通信。goroutine和channel是 Go 语言秉承的 CSP(Communicating Sequential Process)并发模式的重要实现基础。 ...

code_AC的博客 2006

Go-一个通用的Golang对象池:设计与实现

对象池(Object Pool)是一种设计模式,用于管理一组可重复使用的资源。资源在此上下文中通常指的是对象实例,它们通常在创建时成本较高,例如数据库连接、线程或大型数据结构等。对象池的主要思想是预先创建一定数量的对象,将它们保存在一个池中,并在需要的时候重复利用这些对象,从而减少重复创建和销毁对象所带来的开销。对象池的主要作用体现在以下几个方面:性能优化:通过重用对象实例,避免了频繁的垃圾回收,从而提高性能。资源管理:控制对象的创建和销毁,防止内存泄漏。并发控制。

weixin_28235889的博客 1124

Go语言的设计模式和BestPractice

1.背景介绍 1. 背景介绍 Go语言,由Google的Robert Griesemer、Rob Pike和Ken Thompson于2009年开发,并于2009年发布。Go语言是一种静态类型、垃圾回收、多线程并发简单的编程语言。Go语言的设计目标是简单、高效、可扩展和易于使用。Go语言的核心设计思想是“简单而不是复杂”。 Go语言的设计模式和BestPractice是Go语言开发者必须掌握...

AI天才研究院 1156

保姆级教程:用MATLAB搞定运动模糊图片修复(附完整代码与避坑指南)

本文提供了一份详细的MATLAB运动模糊图片修复教程,涵盖盲复原、图像复原等核心技术。通过傅里叶变换和Radon变换分析模糊参数,对比逆滤波、维纳滤波和Lucy-Richardson算法效果,并附完整代码与避坑指南,帮助用户实现专业级图像处理。

weixin_26765363的博客 230

【深度剖析】三一重工的数字化转型(中篇)

三一重工在数字化转型方面取得了提高效率、降低成本、加强研发创新和改善内控管理等多方面的成效。本研究旨在通过对三一重工数字化转型的深入分析,引导企业思考在第四次工业革命与第三次能源革命交汇的超级技术窗口期,如何进一步把握发展机遇,并为同行业其他企业提供探索性的建议。作为装备制造行业的佼佼者,三一重工的数字化转型受到了业界的广泛关注。作为行业内首批接触并实践数字化转型的企业之一,三一重工的转型经验不仅成功,而且积累了丰富的理论与实践,为其他制造业企业的数字化转型提供了可借鉴的范例。

领信卓越的博客 2309

Go 语言中的设计模式与实践

1.背景介绍 Go 语言是一种现代编程语言,由 Google 的 Robert Griesemer、Rob Pike 和 Ken Thompson 设计开发。Go 语言旨在解决许多现有编程语言中的一些限制,例如 C++ 的复杂性和 Java 的垃圾回收问题。Go 语言的设计理念是简洁、高效和可扩展性。 Go 语言的设计模式是一种编程方法,它提供了一种结构化的方式来解决常见的编程问题。这些设计模...

AI天才研究院 912

Cadence Design Entry HDL 使用教程

Cadence Design Entry HDL 使用教程 前言 cadence Design Entry HDL是cadence内部集成的一款板级的EDA设计工具,早期叫 concept HDL。其为cadence最早的原配板级电路图绘制工具,只不过由于后来cadence收购了orcad然后就将旗下的capture CIS收入其中,由于后者使用起来上手简单,所以后者更为大家所熟知。虽然大家对...

uio159753的博客 4万+

Go常用设计模式(下)

装饰器模式很容易理解,他就是在我们想要调用方法的时候增加一些额外的操作,这种操作我们就成为装饰,就是让对象经过装饰增加需要的属性或功能。但是Go实现的代理模式和Java实现的相比不太容易理解,所以还需要我们多花一些时间来理解。

做兴趣使然的Hero 418

Nacos漏洞利用工具V3.0.5实战:从认证绕开到内存马植入的全流程指南

本文详细解析了Nacos漏洞利用工具V3.0.5在实战中的应用,从认证绕开到内存马植入的全流程。文章深入探讨了如何利用Nacos的历史漏洞,如默认口令、认证逻辑绕过、Derby SQL注入及Jraft反序列化,实现权限提升与持久化控制,并提供了防御视角与加固建议,旨在帮助安全人员理解攻击链以加强防护。

h6j7k8l9p0的博客 485

SAP CDS View 教程里的标准视图:SEPM_I_SalesOrderItem_E 当成一张表来用之前,你需要先弄清它到底是什么

摘要:SEPM_I_SalesOrderItem_E 是 SAP EPM demo 中的预交付 CDS 视图,用于表示销售订单行项目数据。它采用 VDM 命名规范,_E 后缀表示对外隐藏内部 UUID 键,提供业务友好的外部 ID 接口。该视图常见于 ABAP Platform 7.50+、开发版系统及 Gateway 教程中,可像表一样通过 Open SQL 查询。实际项目中,这类视图能有效解决内外系统键值映射问题,示例代码展示了如何查询其数据。使用时需注意系统是否安装了 EPM demo 内容。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 559

Go并发原语/并发组件/go并发核心语法 之channel

channel: 虽然 他们可以用来同步内存访问; 但他们最好用于在 goroutine 之间传递信息。 命名: 像河流一样,一个channel充当着信息传送的管道,值可以沿着channel传递,然后在下游读出。由于这个特点,通常使用"stream" 来做 chan 变量名的后缀。 创建channel 语句: var dataStream chan interface{} ...

u013862108的博客 2万+

YOLOv13必学核心:SKAttention选择性核注意力机制原理 + 实战全拆解

SKAttention的核心思想来源于人类视觉系统的一个重要特性:根据不同的视觉刺激,人眼能够自适应地调整感受野大小。SKAttention将这一生物学原理转化为深度学习中的注意力机制,通过动态选择和融合不同大小的卷积核,实现了自适应的多尺度特征提取。在人类视觉皮层中,不同的神经元具有不同大小的感受野,而且这些感受野的大小会根据视觉刺激的类型动态调整。本文将深入解析SKAttention模块的设计原理、数学基础、实现细节,以及其在YOLOv13目标检测框架中的集成应用,为读者提供全面而深入的技术理解。

FJN110的博客 97

探索Go语言设计模式之美:全面解读Design Patterns in Golang

探索Go语言设计模式之美:全面解读Design Patterns in Golang 在这个快速迭代的软件开发世界中,设计模式不仅是一种编码技巧,更是提升代码质量和可维护性的宝贵财富。今天,我们深入探讨一个专为Go程序员量身打造的开源宝藏——《Design patterns in golang》。这不仅仅是一份文档,而是一个面向初学者和进阶者的实践指南,旨在通过Go语言实现各种经典设计模式,让开发...

gitblog_00898的博客 742

mbed驱动st7789屏幕-硬件选择及连接(1)

在单片机项目中,交互性至关重要,而视觉感知是用户交互的直接体现。本期专栏介绍了如何使用mbed平台驱动ST7789型号的TFT屏幕,以显示字符、汉字和图像。由于针对STM32L432KC的mbed驱动库尚未完整,作者自行编写了一个基于mbed的ST7789屏幕驱动库,并将在专栏中提供全代码及使用指南。

weixin_64524066的博客 391

X线DR医学图像 --- DR医用滤线栅及摩尔纹详解 (二) 摩尔纹的产生机理

1,横向摩尔纹的表现 2,纵向摩尔纹的表现 3,摩尔纹在pitch = 143μm(注:pitch为采样间隔/周期)的FPD上的表现。 4,摩尔纹的危害(严重的影响了临床诊断) 5,摩尔纹对胸片肺部肺纹理的破坏 6,滤线栅的频率(滤线栅生产厂家的产品参数)。判断摩尔纹产生的重要依据之一 7,DR平板探测器的采样频率/空间极限分辨率 l.........

松下J27录放机 4982

运用多种设计模式的综合案例_Go并发设计模式之 Active Object

点击上方蓝色“Go语言中文网”关注我们,领全套Go资料,每天学习Go语言本文作者:鸟窝smallnest原文链接:https://colobu.com/2019/07/02/concurrency-design-patterns-active-object/设计模式曾经很火,尤其是1995年的时候Erich Gamma, Richard Helm, Ralph Johnson 和 J...

weixin_39703926的博客 331

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

Go语言常用的设计模式

本文系统介绍了24种设计模式在Go语言中的实现,分为创建型、结构型、行为型和Go特有模式四类。创建型模式包括单例、工厂方法等6种实例化模式;结构型模式涵盖适配器、装饰器等7种对象组合方式;行为型模式提供责任链、观察者等7种交互模式;特别针对Go语言特性提出函数选项、并发模式等4种特有实现。所有模式均结合Go语言特性(接口、组合、并发)给出具体代码示例和应用场景,并强调Go语言"组合优于继承"的设计哲学,建议根据实际业务需求选择模式,避免过度设计。

qq_44805265的博客 1194

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

探索 Go 语言之美:golang_design_pattern 项目深度解读

探索 Go 语言之美:golang_design_pattern 项目深度解读 在这个快速迭代的时代,编写高质量、可维护的代码显得尤为重要。《探索 Go 语言之美:golang_design_pattern 项目深度解读》旨在带领各位开发者深入了解一个专注于 Go 语言下设计模式实践的开源项目。该项目不仅是一本活生生的教材,更是提升Go代码优雅度和可扩展性的宝典。 项目介绍 golang_desi...

gitblog_00920的博客 782

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

Everything Claude Code Go语言开发:从Golang模式到测试的完整AI工作流

**Everything Claude Code**是一个完整的Claude Code配置集合,专为Go开发者提供了从代码编写到测试的完整AI工作流。这个由Anthropic黑客马拉松获奖者打造的工具集,为Go语言开发带来了革命性的效率提升。 ## 🚀 Go语言开发的AI助手革命 在Go语言开发中,Everything Claude Code提供了全面的支持体系。通过集成Go代码审查、测试驱

gitblog_01012的博客 902

云原生与Go语言高并发场景

Go语言凭借其原生并发支持卓越的性能表现和丰富的云原生生态,已成为高并发场景下的首选语言。随着容器感知调度、边缘计算和服务网格等新技术的发展,Go语言在云原生领域的地位将进一步巩固。对于开发者而言,掌握Go语言不仅意味着能够构建高性能的云原生应用,更代表着抓住了未来技术发展的脉搏。无论是微服务架构、高并发系统还是边缘计算场景,Go语言都提供了简洁而强大的解决方案。行动建议:想要深入学习Go语言云原生开发?学习Go语言基础语法和并发模型掌握Docker和Kubernetes等云原生技术。

1211

行为型设计模式在Golang中的精妙运用

行为型设计模式在Golang中的精妙运用 【免费下载链接】golang-design-pattern 设计模式 Golang实现-《研磨设计模式》读书笔记 项目地址: https://gitcode.com/gh_mirrors/...

gitblog_00197的博客 791

go的设计模式

在2020年七月最后一个星期,我开始学习了go的设计模式 设计模式 是一套被反复使用、多数人知晓的、经过分类的、代码设计经验的总结 分类 创建型( 单例模式、简单工厂模式、工厂方法模式、抽象厂模式、建造者模式、原型模式) 结构型(代理模式、适配器模式、装饰模式、桥接模式、组合模式、享元模式、外观模式) 行为型(观察者模式、模板方法模式、命令模式、状态模式、职责链模式、解释器模式、中介者模式、访问者模式、策略模式、备忘录模式、迭代器模式) 五大原则 1、开闭原则 开放扩展,关闭修改 开闭原则的主旨是为了

qq_44981657的博客 3488

Go网络编程中的设计模式实战指南

在这篇文章中,我们深入探索了Go网络编程中的五个核心设计模式。每个模式都有其独特的应用场景和价值,但更重要的是,我们学会了如何在实际项目中灵活运用这些模式,构建出高性能、高可靠的网络应用。学习设计模式的最终目标不是记住每个模式的实现细节,而是培养系统性思考问题的能力。正如建筑师不仅要掌握各种建筑技法,更要理解建筑背后的美学和哲学。在网络编程中,我们面对的是一个复杂、动态、不可预测的环境。🎯 理解本质:每个模式解决的核心问题是什么?🔄 灵活应用:如何根据具体场景调整和组合模式?🚀 持续演进。

sinat_27016095的博客 1538

编程笔记 Golang基础 034 异步和并发编程

异步编程和并发编程是软件开发中两种相关的编程范式和技术,它们都涉及同时处理多个任务或操作,但关注点和实现方式有所不同。

明月看潮生的博客 1507
上一篇: 一篇文章搞清电商订单结算页面设计?
下一篇: 由浅到深,入门Go语言Map实现原理
TIGERB_Blog
博客等级 码龄10年 109粉丝 65原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值