重构思路
- 接口抽象:定义一个统一的促销策略接口,所有具体的促销策略类都实现该接口,使得代码依赖于抽象而非具体实现,提高可替换性。
- 策略管理:创建一个策略管理类,负责根据不同条件选择合适的策略实例,避免在业务代码中出现大量的条件判断逻辑,增强代码的可维护性。
- 依赖注入:在需要使用促销策略的地方,通过依赖注入的方式传入具体的策略实例,提高代码的灵活性和扩展性。
主要重构代码片段
- 定义促销策略接口
public interface IPromotionStrategy
{
decimal CalculatePrice(decimal originalPrice);
}
- 具体促销策略类实现接口
public class DiscountStrategy : IPromotionStrategy
{
private readonly decimal _discountRate;
public DiscountStrategy(decimal discountRate)
{
_discountRate = discountRate;
}
public decimal CalculatePrice(decimal originalPrice)
{
return originalPrice * (1 - _discountRate);
}
}
public class FixedPriceStrategy : IPromotionStrategy
{
private readonly decimal _fixedPrice;
public FixedPriceStrategy(decimal fixedPrice)
{
_fixedPrice = fixedPrice;
}
public decimal CalculatePrice(decimal originalPrice)
{
return _fixedPrice;
}
}
- 策略管理类
public class PromotionStrategyManager
{
public static IPromotionStrategy GetStrategy(string promotionType)
{
switch (promotionType.ToLower())
{
case "discount":
return new DiscountStrategy(0.2m); // 假设折扣率为20%
case "fixedprice":
return new FixedPriceStrategy(50); // 假设固定价格为50
default:
throw new ArgumentException("Invalid promotion type");
}
}
}
- 使用依赖注入在业务代码中应用策略
public class Product
{
private readonly decimal _originalPrice;
private readonly IPromotionStrategy _promotionStrategy;
public Product(decimal originalPrice, IPromotionStrategy promotionStrategy)
{
_originalPrice = originalPrice;
_promotionStrategy = promotionStrategy;
}
public decimal GetFinalPrice()
{
return _promotionStrategy.CalculatePrice(_originalPrice);
}
}
- 调用示例
class Program
{
static void Main()
{
var strategy = PromotionStrategyManager.GetStrategy("discount");
var product = new Product(100, strategy);
var finalPrice = product.GetFinalPrice();
Console.WriteLine($"Final price: {finalPrice}");
}
}