面试题答案
一键面试设计思路
- 定义空接口:使用Go语言的空接口
interface{}
作为所有交易类型的通用接口,每种具体交易类型实现该接口定义的方法。 - 交易类型结构体:针对每种交易类型(股票、期货、外汇等),定义各自的结构体,包含该交易类型特有的数据字段。
- 接口方法实现:为每种交易类型结构体实现空接口定义的方法,方法内包含具体的交易处理逻辑。
- 扩展性:通过实现空接口的方式,新的交易类型可以很容易地添加进来,只需要定义新的结构体并实现空接口的方法即可。
- 性能优化:使用Go语言的并发特性,对于不同的交易请求可以并发处理,提高系统整体性能。同时,合理使用内存,避免不必要的内存分配。
- 错误处理:在每个交易处理方法中,返回合适的错误信息,调用方可以根据返回的错误进行相应处理。
关键代码示例
package main
import (
"fmt"
)
// 定义交易处理接口
type TransactionHandler interface {
Process() (string, error)
}
// 股票交易结构体
type StockTransaction struct {
Symbol string
Quantity int
Price float64
}
// 实现股票交易处理方法
func (s StockTransaction) Process() (string, error) {
if s.Quantity <= 0 {
return "", fmt.Errorf("invalid quantity: %d", s.Quantity)
}
total := s.Quantity * s.Price
return fmt.Sprintf("Stock transaction processed. Total: %.2f", total), nil
}
// 期货交易结构体
type FuturesTransaction struct {
Contract string
Expiry string
Amount float64
}
// 实现期货交易处理方法
func (f FuturesTransaction) Process() (string, error) {
if f.Amount <= 0 {
return "", fmt.Errorf("invalid amount: %.2f", f.Amount)
}
return fmt.Sprintf("Futures transaction processed. Amount: %.2f", f.Amount), nil
}
// 外汇交易结构体
type ForexTransaction struct {
FromCurrency string
ToCurrency string
Rate float64
Amount float64
}
// 实现外汇交易处理方法
func (f ForexTransaction) Process() (string, error) {
if f.Amount <= 0 {
return "", fmt.Errorf("invalid amount: %.2f", f.Amount)
}
converted := f.Amount * f.Rate
return fmt.Sprintf("Forex transaction processed. Converted amount: %.2f", converted), nil
}
// 处理交易请求
func HandleTransaction(t TransactionHandler) {
result, err := t.Process()
if err != nil {
fmt.Printf("Transaction failed: %v\n", err)
} else {
fmt.Println(result)
}
}
func main() {
stock := StockTransaction{Symbol: "AAPL", Quantity: 10, Price: 150.0}
futures := FuturesTransaction{Contract: "CL2306", Expiry: "2023-06-30", Amount: 5000.0}
forex := ForexTransaction{FromCurrency: "USD", ToCurrency: "CNY", Rate: 6.5, Amount: 1000.0}
HandleTransaction(stock)
HandleTransaction(futures)
HandleTransaction(forex)
}
在上述代码中:
- 定义了
TransactionHandler
接口,包含Process
方法。 - 分别定义了
StockTransaction
、FuturesTransaction
和ForexTransaction
结构体,并为它们实现了Process
方法。 HandleTransaction
函数接受一个实现了TransactionHandler
接口的对象,调用其Process
方法并处理可能返回的错误。- 在
main
函数中,创建了不同类型的交易实例,并通过HandleTransaction
函数进行处理。