MST
星途 面试题库

面试题:Go语言接口设计模式之策略模式案例分析

在Go语言中,以电商平台不同促销策略为例,如满减、打折,设计实现一个策略模式的接口和具体实现。请阐述设计思路并给出主要代码示例。
13.5万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 定义策略接口:创建一个接口,包含应用促销策略的方法。不同的促销策略(满减、打折)都实现这个接口。
  2. 实现具体策略:分别实现满减和打折策略的结构体及接口方法。
  3. 使用策略:在电商平台的订单计算场景中,根据具体需求选择不同的促销策略进行计算。

主要代码示例

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())
}