面试题答案
一键面试设计思路
- 定义策略接口:创建一个接口,包含应用促销策略的方法。不同的促销策略(满减、打折)都实现这个接口。
- 实现具体策略:分别实现满减和打折策略的结构体及接口方法。
- 使用策略:在电商平台的订单计算场景中,根据具体需求选择不同的促销策略进行计算。
主要代码示例
package main
import "fmt"
// 定义促销策略接口
type PromotionStrategy interface {
ApplyPromotion(amount float64) float64
}
// 满减策略结构体
type FullReduction struct {
FullAmount float64
Reduce float64
}
// 满减策略实现接口方法
func (fr FullReduction) ApplyPromotion(amount float64) float64 {
if amount >= fr.FullAmount {
return amount - fr.Reduce
}
return amount
}
// 打折策略结构体
type Discount struct {
Rate float64
}
// 打折策略实现接口方法
func (d Discount) ApplyPromotion(amount float64) float64 {
return amount * d.Rate
}
// 订单结构体
type Order struct {
Amount float64
Strategy PromotionStrategy
}
// 计算订单最终金额
func (o Order) CalculateFinalAmount() float64 {
return o.Strategy.ApplyPromotion(o.Amount)
}
可以这样使用:
func main() {
// 满减策略,满200减50
fullReduction := FullReduction{FullAmount: 200, Reduce: 50}
// 打折策略,打8折
discount := Discount{Rate: 0.8}
// 订单1,金额300,使用满减策略
order1 := Order{Amount: 300, Strategy: fullReduction}
fmt.Printf("订单1最终金额: %.2f\n", order1.CalculateFinalAmount())
// 订单2,金额150,使用打折策略
order2 := Order{Amount: 150, Strategy: discount}
fmt.Printf("订单2最终金额: %.2f\n", order2.CalculateFinalAmount())
}