工厂模式(Factory Pattern)是面向对象编程中一种常见的创建型设计模式,用于封装和管理对象的创建过程,将对象的实例化逻辑与使用逻辑分离。其核心思想是通过工厂类来代替直接使用 new 关键字创建对象,从而提高代码的灵活性、可维护性和可扩展性。

1.工厂模式的核心思想

解耦:将对象的创建与使用分离,客户端无需知道具体产品的类名或实现细节。
统一管理:通过工厂类集中控制对象的创建逻辑,便于后续扩展或修改。
灵活扩展:新增产品时,只需扩展工厂逻辑,而无需修改原有代码(符合开闭原则)。

2. go 项目电商系统中工厂模式使用举例

package main

import "fmt"

// 产品接口
type Product interface {
	Operation() string
}

// 具体产品A
type ConcreteProductA struct{}

func (p *ConcreteProductA) Operation() string {
	return "Result of ConcreteProductA"
}

// 具体产品B
type ConcreteProductB struct{}

func (p *ConcreteProductB) Operation() string {
	return "Result of ConcreteProductB"
}

// 工厂函数
func NewProduct(productType string) Product {
	switch productType {
	case "A":
		return &ConcreteProductA{}
	case "B":
		return &ConcreteProductB{}
	default:
		panic("Unknown product type")
	}
}

func main() {
	productA := NewProduct("A")
	fmt.Println(productA.Operation()) // 输出 Result of ConcreteProductA

	productB := NewProduct("B")
	fmt.Println(productB.Operation()) // 输出 Result of ConcreteProductB
}

3. 电商系统中的工厂模式优化实践

优化点1:缓存产品实例
  • 问题:频繁创建相同类型的产品实例可能导致性能浪费。
  • 优化:使用缓存(如 sync.Map)存储已创建的实例。
    var productCache = sync.Map{}
    
    func NewProduct(productType string) (Product, error) {
        if cached, ok := productCache.Load(productType); ok {
            return cached.(Product), nil
        }
    
        var product Product
        switch productType {
        case "A":
            product = &ConcreteProductA{}
        case "B":
            product = &ConcreteProductB{}
        default:
            return nil, fmt.Errorf("unknown product type: %s", productType)
        }
    
        productCache.Store(productType, product)
        return product, nil
    }
    
优化点2:支持动态扩展产品类型
  • 问题:新增产品类型时需要修改 switch 逻辑,违反开闭原则。
  • 优化:使用注册表(Registry)动态注册产品类型。
    type Creator func() Product
    
    var creators = map[string]Creator{}
    
    func RegisterProduct(productType string, creator Creator) {
        creators[productType] = creator
    }
    
    func NewProduct(productType string) (Product, error) {
        if creator, exists := creators[productType]; exists {
            return creator(), nil
        }
        return nil, fmt.Errorf("unknown product type: %s", productType)
    }
    
    // 注册产品类型
    func init() {
        RegisterProduct("A", func() Product { return &ConcreteProductA{} })
        RegisterProduct("B", func() Product { return &ConcreteProductB{} })
    }
    
优化点3:接口兼容性设计
  • 问题:若接口方法使用指针接收器,值类型可能无法实现接口。

  • 优化:统一使用指针接收器实现接口方法。

    // 定义接口
    type Product interface {
        Operation() string
    }
    
    // 使用指针接收器实现接口
    func (p *ConcreteProductA) Operation() string {
        return "Result of ConcreteProductA"
    }
    
    func (p *ConcreteProductB) Operation() string {
        return "Result of ConcreteProductB"
    }
    

    |

在电商系统中,工厂模式的设计需要结合业务需求权衡性能、安全性和扩展性。通过合理选择接收器类型,并结合缓存、注册表等优化手段,可以构建高效且可维护的系统架构。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐