定义一系列算法,将每个算法封装起来,使它们可以互换。
需要在运行时选择不同的算法或行为。
定义策略接口,通过依赖注入切换实现。
1// Gas 价格策略接口2type GasPriceStrategy interface {3 GetGasPrice(ctx context.Context) (*big.Int, error)4}5 6// 固定 Gas 价格7type FixedGasPrice struct {8 price *big.Int9}10 11func (f *FixedGasPrice) GetGasPrice(ctx context.Context) (*big.Int, error) {12 return f.price, nil13}14 15// 动态 Gas 价格(从节点获取)16type DynamicGasPrice struct {17 client *ethclient.Client18}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.Client27 tip *big.Int28}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), nil33}34 35// 交易服务使用策略36type TxService struct {37 strategy GasPriceStrategy38}39 40func (s *TxService) SendTx(ctx context.Context, tx *types.Transaction) error {41 gasPrice, _ := s.strategy.GetGasPrice(ctx)42 // 使用 gasPrice 发送交易43}根据网络拥堵情况动态选择 Gas 价格策略。