面试题答案
一键面试- 接口组合模式的作用:
- 在微服务架构的电商系统中,接口组合模式能将复杂的功能拆分成多个小的接口,然后通过组合这些小接口来构建更复杂的接口。这样可以使各模块依赖于抽象的接口,而不是具体的实现,从而实现解耦。同时,当系统需要扩展新功能时,只需要实现新的接口并进行组合即可,提高了扩展性。对于维护性来说,由于模块间依赖减少,修改一个模块的实现不会影响到其他依赖其接口的模块。
- 关键代码示例:
- 定义基础接口:
// 库存管理接口 type Inventory interface { CheckStock(productID string, quantity int) bool DeductStock(productID string, quantity int) error } // 用户认证接口 type UserAuthenticator interface { Authenticate(userID, password string) bool }
- 订单处理模块依赖的接口:
// 订单处理依赖库存和用户认证接口 type OrderProcessor interface { CreateOrder(userID string, productID string, quantity int) error } type orderProcessor struct { inventory Inventory authenticator UserAuthenticator } func NewOrderProcessor(inv Inventory, auth UserAuthenticator) OrderProcessor { return &orderProcessor{ inventory: inv, authenticator: auth, } } func (op *orderProcessor) CreateOrder(userID string, productID string, quantity int) error { if!op.authenticator.Authenticate(userID, "password") { return fmt.Errorf("user authentication failed") } if!op.inventory.CheckStock(productID, quantity) { return fmt.Errorf("insufficient stock") } return op.inventory.DeductStock(productID, quantity) }
- 模拟库存管理实现:
type mockInventory struct { stock map[string]int } func NewMockInventory() Inventory { return &mockInventory{ stock: make(map[string]int), } } func (mi *mockInventory) CheckStock(productID string, quantity int) bool { if stock, ok := mi.stock[productID]; ok { return stock >= quantity } return false } func (mi *mockInventory) DeductStock(productID string, quantity int) error { if stock, ok := mi.stock[productID]; ok { if stock < quantity { return fmt.Errorf("insufficient stock for deduction") } mi.stock[productID] -= quantity return nil } return fmt.Errorf("product not found in stock") }
- 模拟用户认证实现:
type mockUserAuthenticator struct{} func NewMockUserAuthenticator() UserAuthenticator { return &mockUserAuthenticator{} } func (mua *mockUserAuthenticator) Authenticate(userID, password string) bool { // 简单模拟认证逻辑 return userID == "validUser" && password == "validPassword" }
- 使用示例:
func main() { inv := NewMockInventory() auth := NewMockUserAuthenticator() orderProcessor := NewOrderProcessor(inv, auth) err := orderProcessor.CreateOrder("validUser", "product1", 10) if err != nil { fmt.Println("Create order error:", err) } else { fmt.Println("Order created successfully") } }
- 定义基础接口:
在上述代码中,订单处理模块通过组合库存管理接口和用户认证接口来完成订单创建功能。这样,库存管理模块和用户认证模块可以独立开发、测试和维护,并且当需要更换库存管理或用户认证的实现时,只需要实现对应的接口,订单处理模块不需要进行大的改动,提高了系统的可维护性和扩展性。