文章目录
1. 单例模式 (Singleton)
场景:全局唯一配置管理、数据库连接池
Go实现:
type Config struct {
Port int
}
var (
instance *Config
once sync.Once
)
func GetConfig() *Config {
once.Do(func() { // 线程安全初始化
instance = &Config{Port: 8080}
})
return instance
}
2. 工厂模式 (Factory)
场景:根据不同条件创建不同数据库驱动(MySQL/PostgreSQL)
Go实现:
type Database interface {
Connect() string
}
type MySQL struct{}
func (m MySQL) Connect() string { return "MySQL connected" }
type PostgreSQL struct{}
func (p PostgreSQL) Connect() string { return "PostgreSQL connected" }
func NewDatabase(dbType string) Database {
switch dbType {
case "mysql":
return &MySQL{}
case "postgres":
return &PostgreSQL{}
default:
panic("unsupported database type")
}
}
3. 观察者模式 (Observer)
场景:订单状态变更通知(短信、邮件、App推送)
Go实现:
type Observer interface {
Update(msg string)
}
type OrderSubject struct {
observers []Observer
}
func (o *OrderSubject) Attach(ob Observer) {
o.observers = append(o.observers, ob)
}
func (o *OrderSubject) Notify(msg string) {
for _, ob := range o.observers {
ob.Update(msg)
}
}
// 具体观察者
type EmailNotifier struct{}
func (e EmailNotifier) Update(msg string) {
fmt.Printf("Email sent: %s\n", msg)
}
4. 策略模式 (Strategy)
场景:支付方式切换(支付宝/微信/银行卡)
Go实现:
type PaymentStrategy interface {
Pay(amount float64) string
}
type Alipay struct{}
func (a Alipay) Pay(amount float64) string {
return fmt.Sprintf("Paid %.2f via Alipay", amount)
}
type WechatPay struct{}
func (w WechatPay) Pay(amount float64) string {
return fmt.Sprintf("Paid %.2f via Wechat", amount)
}
type PaymentContext struct {
strategy PaymentStrategy
}
func (p *PaymentContext) Execute(amount float64) string {
return p.strategy.Pay(amount)
}
5. 代理模式 (Proxy)
场景:API请求缓存、权限校验
Go实现:
type RealAPI struct{}
func (r RealAPI) Request() string {
return "Real API Response"
}
type ProxyAPI struct {
realAPI RealAPI
cache string
cacheTTL time.Time
}
func (p *ProxyAPI) Request() string {
if time.Now().Before(p.cacheTTL) {
return "Cached: " + p.cache
}
res := p.realAPI.Request()
p.cache = res
p.cacheTTL = time.Now().Add(5 * time.Minute)
return res
}
6. 模板方法模式 (Template Method)
场景:标准化HTTP请求处理流程
核心思想:定义算法的骨架(固定流程),将具体步骤延迟到子类实现,保证结构统一且允许扩展细节。
关键特点:
纵向控制:父类控制整体流程,子类填充具体步骤
代码复用:公共逻辑在父类实现,避免重复
扩展性:新增子类即可扩展新行为,不修改父类
应用场景:
流程标准化:如订单处理(验证 → 支付 → 发货)
框架扩展点:如Spring的JdbcTemplate(定义连接/执行/关闭流程,子类实现SQL)
业务模板:如保险理赔流程(报案 → 审核 → 打款)
Go实现:
type HTTPHandler interface {
Validate() error
Process() string
Log()
}
type BaseHandler struct{}
func (b BaseHandler) Log() {
fmt.Println("Request logged")
}
type UserHandler struct {
BaseHandler
}
func (u UserHandler) Validate() error {
fmt.Println("User validation")
return nil
}
func (u UserHandler) Process() string {
return "User processed"
}
func ExecuteHandler(h HTTPHandler) string {
if err := h.Validate(); err != nil {
return "Validation failed"
}
res := h.Process()
h.Log()
return res
}
// 抽象订单处理流程
type OrderProcessor interface {
Validate() error // 子类实现
Pay() error // 子类实现
Ship() error // 子类实现
}
// 模板方法:定义固定流程
func ProcessOrder(p OrderProcessor) error {
if err := p.Validate(); err != nil {
return err
}
if err := p.Pay(); err != nil {
return err
}
return p.Ship()
}
// 具体实现:国内订单
type DomesticOrder struct{}
func (d DomesticOrder) Validate() error {
fmt.Println("校验国内地址")
return nil
}
func (d DomesticOrder) Pay() error {
fmt.Println("微信支付")
return nil
}
func (d DomesticOrder) Ship() error {
fmt.Println("顺丰发货")
return nil
}
// 使用
ProcessOrder(DomesticOrder{})
7. 责任链模式 (Chain of Responsibility)
场景:请求处理链(认证 → 限流 → 业务处理)
核心思想:将多个处理器串联成链,请求沿链传递,每个处理器决定处理或传递,实现动态流程编排。
关键特点:
横向扩展:动态增减处理器,灵活调整流程顺序
解耦:发送者无需知道具体处理者
短路机制:任一节点处理成功可终止传递
应用场景:
多级校验:如商品创建(空值 → 价格 → 库存校验)
审批流程:如请假审批(组长 → 经理 → CEO)
拦截器链:如HTTP中间件(认证 → 日志 → 限流)
Go实现:
type Handler interface {
SetNext(h Handler)
Handle(request string)
}
type AuthHandler struct {
next Handler
}
func (a *AuthHandler) SetNext(h Handler) { a.next = h }
func (a *AuthHandler) Handle(req string) {
fmt.Println("Auth check passed")
if a.next != nil {
a.next.Handle(req)
}
}
type RateLimitHandler struct {
next Handler
}
func (r *RateLimitHandler) SetNext(h Handler) { r.next = h }
func (r *RateLimitHandler) Handle(req string) {
fmt.Println("Rate limit check passed")
if r.next != nil {
r.next.Handle(req)
}
}
// 客户端调用
chain := &AuthHandler{}
chain.SetNext(&RateLimitHandler{})
chain.Handle("request")
代码案例:
// 处理器接口
type Handler interface {
Handle(request string) bool // 返回是否处理成功
SetNext(h Handler)
}
// 空值校验处理器
type NullCheckHandler struct {
next Handler
}
func (n *NullCheckHandler) Handle(req string) bool {
if req == "" {
fmt.Println("错误:请求为空")
return false
}
if n.next != nil {
return n.next.Handle(req)
}
return true
}
func (n *NullCheckHandler) SetNext(h Handler) { n.next = h }
// 价格校验处理器
type PriceCheckHandler struct {
next Handler
}
func (p *PriceCheckHandler) Handle(req string) bool {
if strings.Contains(req, "price=0") {
fmt.Println("错误:价格不能为0")
return false
}
if p.next != nil {
return p.next.Handle(req)
}
return true
}
func (p *PriceCheckHandler) SetNext(h Handler) { p.next = h }
// 使用
chain := &NullCheckHandler{}
chain.SetNext(&PriceCheckHandler{})
success := chain.Handle("create product?price=100&stock=10")
结合:模板方法 + 责任链
场景:电商秒杀系统下单流程
需求:固定流程(风控 → 扣库存 → 创建订单),其中风控包含多级动态校验(黑名单 → 频率 → 地域)
// 1. 模板方法定义整体流程:
type SecKillProcessor interface {
RiskControl() error // 责任链实现
DeductStock() error
CreateOrder() error
}
func Process(p SecKillProcessor) error {
if err := p.RiskControl(); err != nil {
return err
}
if err := p.DeductStock(); err != nil {
return err
}
return p.CreateOrder()
}
// 2. 责任链模式实现风控:
// 风控处理器链
type RiskHandler interface {
Handle(userID string) error
SetNext(h RiskHandler)
}
type BlacklistHandler struct { next RiskHandler }
func (b *BlacklistHandler) Handle(userID string) error {
if isInBlacklist(userID) {
return errors.New("黑名单用户")
}
if b.next != nil {
return b.next.Handle(userID)
}
return nil
}
type FrequencyHandler struct { next RiskHandler }
func (f *FrequencyHandler) Handle(userID string) error {
if getRequestCount(userID) > 5 {
return errors.New("请求过于频繁")
}
if f.next != nil {
return f.next.Handle(userID)
}
return nil
}
// 在SecKillProcessor实现中组合责任链
type SecKillImpl struct {}
func (s SecKillImpl) RiskControl() error {
chain := &BlacklistHandler{}
chain.SetNext(&FrequencyHandler{})
return chain.Handle("user123")
}