当前位置: 首页 > news >正文

Go语言设计模式:结构型模式

Go语言设计模式结构型模式一、结构型模式概述结构型模式关注如何组合类和对象以形成更大的结构同时保持结构的灵活性和高效性。Go语言中的结构型模式特点组合优于继承使用嵌入实现代码复用接口组合通过接口定义行为契约关注点分离通过模式解耦不同职责二、适配器模式适配器模式将一个类的接口转换成客户希望的另一个接口使原本不兼容的类可以协同工作。对象适配器package adapter type Target interface { Request() string } type Adaptee struct{} func (a *Adaptee) SpecificRequest() string { return Specific request } type Adapter struct { adaptee *Adaptee } func (a *Adapter) Request() string { return a.adaptee.SpecificRequest() } func main() { var target Target Adapter{adaptee: Adaptee{}} println(target.Request()) }接口适配器使用嵌入package adapter import fmt type LegacyService struct{} func (l *LegacyService) OldMethod(data []byte) error { fmt.Printf(Legacy method called with: %s\n, data) return nil } type NewInterface interface { Process(data []byte) error } type LegacyAdapter struct { *LegacyService } func (a *LegacyAdapter) Process(data []byte) error { return a.OldMethod(data) }三、桥接模式桥接模式将抽象部分与实现部分分离使它们可以独立变化。package bridge type Implementor interface { OperationImpl() string } type ConcreteImplementorA struct{} func (c *ConcreteImplementorA) OperationImpl() string { return Implementation A } type ConcreteImplementorB struct{} func (c *ConcreteImplementorB) OperationImpl() string { return Implementation B } type Abstraction struct { implementor Implementor } func (a *Abstraction) Operation() string { return a.implementor.OperationImpl() } type RefinedAbstraction struct { Abstraction } func (r *RefinedAbstraction) ExtendedOperation() string { return Extended: r.Operation() }四、组合模式组合模式将对象组合成树形结构以表示部分-整体的层次结构。package composite type Component interface { Operation() string } type Leaf struct { name string } func (l *Leaf) Operation() string { return Leaf: l.name } type Composite struct { children []Component } func (c *Composite) Add(child Component) { c.children append(c.children, child) } func (c *Composite) Remove(child Component) { for i, ch : range c.children { if ch child { c.children append(c.children[:i], c.children[i1:]...) break } } } func (c *Composite) Operation() string { result : Composite: [ for i, child : range c.children { if i 0 { result , } result child.Operation() } result ] return result }五、装饰器模式装饰器模式动态地给对象添加额外的职责比继承更灵活。package decorator type Component interface { Operation() string } type ConcreteComponent struct{} func (c *ConcreteComponent) Operation() string { return ConcreteComponent } type Decorator struct { component Component } func (d *Decorator) Operation() string { return d.component.Operation() } type ConcreteDecoratorA struct { Decorator } func (c *ConcreteDecoratorA) Operation() string { return DecoratorA( c.component.Operation() ) } type ConcreteDecoratorB struct { Decorator } func (c *ConcreteDecoratorB) Operation() string { return DecoratorB( c.component.Operation() ) }六、外观模式外观模式为子系统中的一组接口提供一个统一的高层接口简化客户端使用。package facade import fmt type SubsystemA struct{} func (s *SubsystemA) OperationA() { fmt.Println(Subsystem A operation) } type SubsystemB struct{} func (s *SubsystemB) OperationB() { fmt.Println(Subsystem B operation) } type SubsystemC struct{} func (s *SubsystemC) OperationC() { fmt.Println(Subsystem C operation) } type Facade struct { subsystemA *SubsystemA subsystemB *SubsystemB subsystemC *SubsystemC } func NewFacade() *Facade { return Facade{ subsystemA: SubsystemA{}, subsystemB: SubsystemB{}, subsystemC: SubsystemC{}, } } func (f *Facade) ComplexOperation() { f.subsystemA.OperationA() f.subsystemB.OperationB() f.subsystemC.OperationC() } func (f *Facade) SimpleOperation() { f.subsystemA.OperationA() f.subsystemC.OperationC() }七、享元模式享元模式通过共享对象来减少内存使用适合处理大量相似对象。package flyweight import sync type Flyweight interface { Operation(extrinsicState string) string } type ConcreteFlyweight struct { intrinsicState string } func (c *ConcreteFlyweight) Operation(extrinsicState string) string { return Intrinsic: c.intrinsicState , Extrinsic: extrinsicState } type FlyweightFactory struct { flyweights map[string]Flyweight mu sync.RWMutex } func NewFlyweightFactory() *FlyweightFactory { return FlyweightFactory{ flyweights: make(map[string]Flyweight), } } func (f *FlyweightFactory) GetFlyweight(key string) Flyweight { f.mu.RLock() if flyweight, ok : f.flyweights[key]; ok { f.mu.RUnlock() return flyweight } f.mu.RUnlock() f.mu.Lock() defer f.mu.Unlock() // 双重检查 if flyweight, ok : f.flyweights[key]; ok { return flyweight } flyweight : ConcreteFlyweight{intrinsicState: key} f.flyweights[key] flyweight return flyweight }八、代理模式代理模式为其他对象提供代理控制对原对象的访问。虚拟代理package proxy type Subject interface { Request() string } type RealSubject struct{} func (r *RealSubject) Request() string { // 可能是耗时操作 return Real subject response } type Proxy struct { realSubject *RealSubject } func (p *Proxy) Request() string { // 懒加载 if p.realSubject nil { p.realSubject RealSubject{} } return p.realSubject.Request() }保护代理package proxy type ProtectedSubject struct { userRole string } func (p *ProtectedSubject) Request() string { return Protected data } type ProtectionProxy struct { realSubject *ProtectedSubject userRole string } func (p *ProtectionProxy) Request() string { if p.userRole ! admin { return Access denied } if p.realSubject nil { p.realSubject ProtectedSubject{} } return p.realSubject.Request() }九、结构型模式实战场景API网关作为外观模式package facade type UserService interface { GetUser(id int) (string, error) } type OrderService interface { GetOrders(userID int) ([]string, error) } type PaymentService interface { GetBalance(userID int) (float64, error) } type APIGateway struct { userService UserService orderService OrderService paymentService PaymentService } func (g *APIGateway) GetUserDashboard(userID int) (map[string]interface{}, error) { user, err : g.userService.GetUser(userID) if err ! nil { return nil, err } orders, err : g.orderService.GetOrders(userID) if err ! nil { return nil, err } balance, err : g.paymentService.GetBalance(userID) if err ! nil { return nil, err } return map[string]interface{}{ user: user, orders: orders, balance: balance, }, nil }十、总结结构型设计模式帮助我们组织代码结构适配器模式转换接口使不兼容的类协同工作桥接模式分离抽象与实现组合模式树形结构统一处理单个对象和组合对象装饰器模式动态添加职责外观模式简化复杂系统的接口享元模式共享对象减少内存代理模式控制对象访问在Go语言中应用这些模式时要充分利用接口和组合特性保持代码的简洁性和可维护性。
http://www.gsyq.cn/news/1297448.html

相关文章:

  • C++高效神器 boost::circular_buffer 深度解析与实战
  • 沁恒CH582实战:从模拟SPI到硬件SPI的SD卡性能跃迁与功耗优化全解析
  • KubeDiagrams在监控系统中的应用:Kube Prometheus Stack完整解析
  • 终极指南:如何一键破解Cursor Pro限制,免费享受无限AI编程助手
  • osu!framework 项目模板详解:从空项目到完整游戏
  • 为什么你的Windows系统总是越用越慢?Winhance中文版终极解决方案
  • 植物大战僵尸 (火影版 植物娘版 二战版)官方正版2026最新版pc免费下载(看到请立即转存 资源随时失效)手机版通用
  • 实时流处理专家指南:Apache Spark Streaming架构与最佳实践
  • osu!framework 动画系统详解:从简单旋转到复杂序列
  • 如何轻松解决Windows运行库问题:Visual C++ Redistributable AIO终极指南
  • Adobe-GenP 3.0:5分钟解锁Adobe全家桶的免费激活神器
  • Downr1n实战指南:利用Checkm8漏洞实现iOS设备专业级降级
  • 光与影:33 号远征队mod整合包下载分享2026最新版
  • Workerman-todpole 部署实战:Linux/Windows 环境配置与优化技巧 [特殊字符]
  • AudioSep HuggingFace集成指南:轻松加载预训练模型
  • 3分钟极速部署Windows包管理器:winget-install一键安装指南
  • 植物大战僵尸 (废物版 杂交版 融合版)2026最新版免费下载(看到请立即转存 资源随时失效)pc手机通用
  • 盘点那些能让性能翻倍的C++现代特性
  • 英雄联盟终极自动化工具:LeagueAkari 免费完整指南,告别繁琐操作
  • Notion API Go客户端完整教程:从安装到实战应用的终极指南
  • 植物大战僵尸 (长城版)官方正版2026最新版pc免费下载(看到请立即转存 资源随时失效)手机版通用
  • ARM核心板选型指南:从连接器到软件生态的嵌入式开发实战
  • Taotoken模型广场在技术选型与对比测试中的价值
  • Bandit源码解析:理解纯Elixir HTTP服务器的核心架构
  • Delorean实战:构建企业级时间管理系统的完整教程
  • 保姆级教程:手把手教你用‘版本降级法’搞定PyTorch 1.9.1 + CUDA 11.1环境搭建
  • 别再手动画墙了!用Gazebo建筑编辑器5分钟搞定你的机器人仿真场景
  • UP Squared i12边缘AI开发板:12代酷睿与MIPI-CSI的嵌入式实战
  • NDVI计算
  • 鸿蒙微内核架构解析:从IPC优化到形式化验证的安全设计