golang-design-pattern文档详解:每个设计模式的实现说明
·
golang-design-pattern文档详解:每个设计模式的实现说明
该项目是《研磨设计模式》读书笔记的Golang实现,包含23种设计模式的完整代码实现。本文档将详细介绍每个设计模式的实现方式、核心代码及使用场景,帮助开发者快速理解和应用设计模式。
项目结构
项目采用分类目录结构组织,将设计模式分为创建型、结构型和行为型三大类,每类包含多个具体模式实现:
- 创建型模式:00_simple_factory/、03_singleton/、04_factory_method/、05_abstract_factory/、06_builder/、07_prototype/
- 结构型模式:01_facade/、02_adapter/、09_proxy/、13_composite/、18_flyweight/、20_decorator/、22_bridge/
- 行为型模式:08_mediator/、10_observer/、11_command/、12_iterator/、14_template_method/、15_strategy/、16_state/、17_memento/、19_interpreter/、21_chain_of_responsibility/、23_visitor/
创建型模式
简单工厂模式(Simple Factory)
00_simple_factory/实现了通过类型参数创建不同产品实例的功能。核心代码通过NewAPI(t int) API函数根据输入类型返回对应的接口实现:
// [00_simple_factory/simple.go](https://link.gitcode.com/i/f3742bd4b4d9e91aa4aae23776acc43c)
type API interface {
Say(name string) string
}
func NewAPI(t int) API {
if t == 1 {
return &hiAPI{}
} else if t == 2 {
return &helloAPI{}
}
return nil
}
适用场景:需要根据不同条件创建不同对象,且产品种类较少的场景。
单例模式(Singleton)
03_singleton/使用sync.Once保证对象只被初始化一次,线程安全地实现了单例模式:
// [03_singleton/singleton.go](https://link.gitcode.com/i/ce39fdca22ce800fb58b642a6be20dc0)
var (
instance *singleton
once sync.Once
)
func GetInstance() Singleton {
once.Do(func() {
instance = &singleton{}
})
return instance
}
适用场景:全局配置、数据库连接池等需要唯一实例的场景。
结构型模式
适配器模式(Adapter)
02_adapter/通过适配器将不兼容的接口转换为统一接口,核心实现如下:
// [02_adapter/adapter.go](https://link.gitcode.com/i/f0ebac88088d7afa9461768e649ffa5a)
type Target interface {
Request() string
}
type adapter struct {
Adaptee
}
func (a *adapter) Request() string {
return a.SpecificRequest()
}
适用场景:系统集成时需要适配不同接口的场景。
外观模式(Facade)
01_facade/为多个子系统提供统一接口,简化系统访问:
// [01_facade/facade.go](https://link.gitcode.com/i/65a0f526a305ce3bdc10dd3fc179767a)
type API interface {
Test() string
}
type apiImpl struct {
a AModuleAPI
b BModuleAPI
}
func (a *apiImpl) Test() string {
aRet := a.a.TestA()
bRet := a.b.TestB()
return fmt.Sprintf("%s\n%s", aRet, bRet)
}
适用场景:复杂系统需要简化接口,或需要隔离子系统变化的场景。
行为型模式
观察者模式(Observer)
10_observer/实现了对象间的一对多依赖关系,当主题对象状态变化时,所有观察者都会收到通知。
策略模式(Strategy)
15_strategy/定义了算法族,使它们可以互相替换,让算法变化独立于使用算法的客户。
如何使用
- 克隆项目:
git clone https://gitcode.com/gh_mirrors/go/golang-design-pattern - 进入对应模式目录,如单例模式:
cd 03_singleton - 运行测试:
go test -v
设计模式选择指南
| 问题场景 | 推荐模式 | 实现路径 |
|---|---|---|
| 对象创建 | 工厂模式/单例模式 | 00_simple_factory/、03_singleton/ |
| 接口适配 | 适配器模式 | 02_adapter/ |
| 结构简化 | 外观模式 | 01_facade/ |
| 行为扩展 | 策略模式/观察者模式 | 15_strategy/、10_observer/ |
通过本文档,开发者可以快速定位所需设计模式的实现代码,理解其核心原理和适用场景。每个模式目录下的测试文件提供了具体使用示例,建议结合README.md和测试代码深入学习。
更多推荐


所有评论(0)