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

策略模式

定义一系列算法,将每个算法封装起来,使它们可以互换。

问题场景

需要在运行时选择不同的算法或行为。

解决方案

定义策略接口,通过依赖注入切换实现。

Go 实现

strategy.go
go
1// Gas 价格策略接口
2type GasPriceStrategy interface {
3 GetGasPrice(ctx context.Context) (*big.Int, error)
4}
5
6// 固定 Gas 价格
7type FixedGasPrice struct {
8 price *big.Int
9}
10
11func (f *FixedGasPrice) GetGasPrice(ctx context.Context) (*big.Int, error) {
12 return f.price, nil
13}
14
15// 动态 Gas 价格(从节点获取)
16type DynamicGasPrice struct {
17 client *ethclient.Client
18}
19
20func (d *DynamicGasPrice) GetGasPrice(ctx context.Context) (*big.Int, error) {
21 return d.client.SuggestGasPrice(ctx)
22}
23
24// EIP-1559 Gas 价格
25type EIP1559GasPrice struct {
26 client *ethclient.Client
27 tip *big.Int
28}
29
30func (e *EIP1559GasPrice) GetGasPrice(ctx context.Context) (*big.Int, error) {
31 baseFee, _ := e.client.SuggestGasTipCap(ctx)
32 return new(big.Int).Add(baseFee, e.tip), nil
33}
34
35// 交易服务使用策略
36type TxService struct {
37 strategy GasPriceStrategy
38}
39
40func (s *TxService) SendTx(ctx context.Context, tx *types.Transaction) error {
41 gasPrice, _ := s.strategy.GetGasPrice(ctx)
42 // 使用 gasPrice 发送交易
43}

Web3 应用场景

根据网络拥堵情况动态选择 Gas 价格策略。

优点

  • +算法可互换
  • +开放封闭原则
  • +消除条件语句

缺点

  • -客户端需了解策略差异
中间件模式Worker Pool
Easy-Go-Web3

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

学习路径

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

资源中心

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

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

Created withbyhardybao