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语言中应用这些模式时要充分利用接口和组合特性保持代码的简洁性和可维护性。
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语言中应用这些模式时要充分利用接口和组合特性保持代码的简洁性和可维护性。