设计模式是 Go 框架中编写可维护和可扩展代码的良好实践。其中包括:单例模式:确保全局范围内只有一个类的实例。工厂模式:创建对象的实例,与对象的创建过程分离。观察者模式:允许一个对象订阅另一个对象的事件。
Go 框架中的设计模式
Go 作为一个现代化的编程语言,提供了强大的工具和功能来构建可维护和可扩展的应用程序。设计模式是编写代码的良好实践,它们提供了可重用的解决方案,使开发人员可以专注于解决特定问题。
单例模式
单例模式确保全局范围内只有一个类的实例。它通常用于创建配置对象或数据库连接等资源。
type Singleton struct{} var instance *Singleton var once sync.Once func GetInstance() *Singleton { once.Do(func() { instance = &Singleton{} }) return instance }
工厂模式
工厂模式创建对象的实例,它可以使应用程序与对象的创建过程分离。这允许应用程序根据配置或条件选择创建哪种对象。
type Factory interface { CreateProduct(string) Product } type Product interface { GetName() string } type ConcreteFactory1 struct{} func (f *ConcreteFactory1) CreateProduct(name string) Product { return &ConcreteProduct1{name: name} } type ConcreteFactory2 struct{} func (f *ConcreteFactory2) CreateProduct(name string) Product { return &ConcreteProduct2{name: name} } func main() { factory1 := &ConcreteFactory1{} product1 := factory1.CreateProduct("Product 1") fmt.Println(product1.GetName()) factory2 := &ConcreteFactory2{} product2 := factory2.CreateProduct("Product 2") fmt.Println(product2.GetName()) }
观察者模式
观察者模式允许一个对象订阅另一个对象的事件。当发布者(目标)的状态发生变化时,它会通知所有订阅者(观察者)。
type Publisher struct { subscribers []Subscriber } func (p *Publisher) AddSubscriber(s Subscriber) { p.subscribers = append(p.subscribers, s) } func (p *Publisher) NotifySubscribers() { for _, s := range p.subscribers { s.Update() } } type Subscriber interface { Update() } type ConcreteSubscriber1 struct{} func (c *ConcreteSubscriber1) Update() { fmt.Println("Subscriber 1 notified") } type ConcreteSubscriber2 struct{} func (c *ConcreteSubscriber2) Update() { fmt.Println("Subscriber 2 notified") } func main() { publisher := &Publisher{} subscriber1 := &ConcreteSubscriber1{} subscriber2 := &ConcreteSubscriber2{} publisher.AddSubscriber(subscriber1) publisher.AddSubscriber(subscriber2) publisher.NotifySubscribers() }
实战案例
假设我们有一个电商应用程序,我们希望实施一个功能,以在用户完成购买后向他们的电子邮件发送订单确认。我们可以使用观察者模式,其中购买管理器(Publisher)负责通知订单服务(Subscriber)。
type PurchaseManager struct { subscribers []OrderService } func (p *PurchaseManager) AddOrderService(s OrderService) { p.subscribers = append(p.subscribers, s) } func (p *PurchaseManager) NotifyOrderServices(orderID int) { for _, s := range p.subscribers { s.ProcessOrder(orderID) } } type OrderService interface { ProcessOrder(int) } type EmailService struct{} func (e *EmailService) ProcessOrder(orderID int) { // Send email confirmation to user } func main() { purchaseManager := &PurchaseManager{} emailService := &EmailService{} purchaseManager.AddOrderService(emailService) purchaseManager.NotifyOrderServices(12345) }