Easy-Go-Web3
知识图谱Go 教程React Web3智能合约
需求分析系统设计设计模式Go 微服务
项目实战DevOps
Go 生态React 生态智能合约生态Web3 生态AI × Web3工具箱Web3 公司远程Web3求职
🎯 AA 工程师面试手册博客
GitHub
返回设计模式
创建型

工厂模式

定义创建对象的接口,让子类决定实例化哪个类。

问题场景

创建不同类型的对象,但不想在客户端代码中硬编码具体类。

解决方案

定义工厂函数或接口,根据参数返回不同的实现。

Go 实现

factory.go
go
1// 链客户端工厂
2type ChainClient interface {
3 GetBalance(address string) (*big.Int, error)
4 SendTransaction(tx *Transaction) (string, error)
5}
6
7func NewChainClient(chainType string) (ChainClient, error) {
8 switch chainType {
9 case "ethereum":
10 return NewEthereumClient()
11 case "polygon":
12 return NewPolygonClient()
13 case "bsc":
14 return NewBSCClient()
15 default:
16 return nil, fmt.Errorf("unsupported chain: %s", chainType)
17 }
18}
19
20// 使用
21client, _ := NewChainClient("polygon")
22balance, _ := client.GetBalance("0x...")

Web3 应用场景

多链钱包服务,根据链类型创建对应的 RPC 客户端。

优点

  • +解耦创建和使用
  • +易于扩展新类型
  • +隐藏实现细节

缺点

  • -增加类的数量
  • -简单场景过度设计
单例模式函数选项模式
Easy-Go-Web3

构建 Go 后端与 Web3 的学习之路。从基础到进阶,从理论到实践,助你成为全栈区块链开发者。

学习路径

  • 知识图谱
  • Go 教程
  • Go 微服务
  • 面试手册

资源中心

  • 工具箱
  • DevOps 工具
  • Web3 生态
  • 博客

© 2025 Easy-Go-Web3. All rights reserved.

Created withbyhardybao