Go语言(Golang)设计模式及代码示例
设计模式是针对常见开发问题的成熟解决方案。在Go语言中,由于其简洁的语法和缺乏经典面向对象编程特性,许多模式呈现出独特的实现方式。本文将深入探讨三类设计模式:创建型、结构型和行为型——并提供Golang实践示例。
无论您是初学者还是经验丰富的Go开发者,只要致力于编写简洁、可复用且可测试的代码,本材料都将为您带来启发。
一、创建型模式
创建型模式管理对象的创建过程。在Go语言中,由于没有构造函数和继承机制,其实现方式尤为精巧。
1.1 单例模式
确保某个类型只有一个实例,并提供全局访问点。在Go中,通常使用sync.Once来实现。
package singleton
import ( "sync")
type Database struct { connection string}
var ( instance *Database once sync.Once)
func GetDatabase() *Database { once.Do(func() { instance = &Database{connection: "postgres://user:pass@localhost/db"} }) return instance}适用场景:连接池、缓存、日志记录器。
1.2 工厂方法模式
定义创建对象的接口,但让子类决定实例化哪个类。在Go中,工厂方法本质上就是返回接口的函数。
package factory
import "fmt"
// 产品接口type INotification interface { Send(message string) string}
// 具体产品type Email struct{}
func (e *Email) Send(msg string) string { return fmt.Sprintf("Email sent: %s", msg)}
type SMS struct{}
func (s *SMS) Send(msg string) string { return fmt.Sprintf("SMS sent: %s", msg)}
// 工厂函数func CreateNotification(notifType string) INotification { switch notifType { case "email": return &Email{} case "sms": return &SMS{} default: return nil }}适用场景:当需要创建的对象类型在运行时才能确定时。
1.3 建造者模式
将复杂对象的构建过程与其表示分离。在Go中,建造者通常是一个包含Setter方法(返回建造者自身以实现链式调用)的结构体。
package builder
type Pizza struct { Size string Cheese bool Pepperoni bool}
type PizzaBuilder struct { pizza Pizza}
func NewPizzaBuilder() *PizzaBuilder { return &PizzaBuilder{}}
func (b *PizzaBuilder) SetSize(size string) *PizzaBuilder { b.pizza.Size = size return b}
func (b *PizzaBuilder) AddCheese() *PizzaBuilder { b.pizza.Cheese = true return b}
func (b *PizzaBuilder) AddPepperoni() *PizzaBuilder { b.pizza.Pepperoni = true return b}
func (b *PizzaBuilder) Build() Pizza { return b.pizza}适用场景:当对象包含大量可选参数时。
二、结构型模式
结构型模式定义如何将对象和类组装成更大的结构,同时保持其灵活性和高效性。
2.1 适配器模式
允许接口不兼容的对象协同工作。在Go中,主要通过接口和包装器结构体实现。
package adapter
import "fmt"
// 目标接口type USB interface { ConnectWithUSB() string}
// 被适配者(不兼容类)type MemoryCard struct{}
func (m *MemoryCard) ReadFromCard() string { return "Data read from memory card"}
// 适配器type CardReader struct { card *MemoryC