定义创建对象的接口,让子类决定实例化哪个类。
创建不同类型的对象,但不想在客户端代码中硬编码具体类。
定义工厂函数或接口,根据参数返回不同的实现。
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...")多链钱包服务,根据链类型创建对应的 RPC 客户端。