c#中设计一个超市打折系统
时间: 2024-12-19 17:24:10 浏览: 9
在C#中设计一个简单的超市打折系统,我们可以考虑以下几个步骤:
1. **实体类**:
- **商品类** (Product): 包含基本属性如名称、原价和ID,以及折扣信息。
```csharp
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal OriginalPrice { get; set; }
public double DiscountRate { get; set; } // 折扣率,通常范围0-1
}
```
2. **优惠策略类** (PromotionStrategy): 定义一种或多种打折规则,比如满额减、特定日期优惠等。
```csharp
public abstract class PromotionStrategy
{
public abstract decimal CalculateDiscount(Product product);
}
// 具体的促销策略例如满额减
public class FixedAmountDiscount : PromotionStrategy
{
private decimal _discountThreshold;
public FixedAmountDiscount(decimal discountThreshold)
{
_discountThreshold = discountThreshold;
}
public override decimal CalculateDiscount(Product product)
{
if (product.OriginalPrice >= _discountThreshold)
return product.OriginalPrice * DiscountRate;
else
return 0;
}
}
```
3. **购物车类** (ShoppingCart) 或 **订单类** (Order): 存储商品列表,并能应用优惠策略计算总价。
```csharp
public class ShoppingCart
{
private List<Product> products = new List<Product>();
private PromotionStrategy promotionStrategy;
public void AddProduct(Product product)
{
products.Add(product);
}
public void ApplyPromotion(PromotionStrategy strategy)
{
foreach (var product in products)
product.Price = product.CalculateFinalPrice(strategy);
}
private decimal CalculateFinalPrice(Product product)
{
return product.OriginalPrice * (1 - promotionStrategy.CalculateDiscount(product));
}
}
```
4. **主程序** (Main):
用户添加商品到购物车,然后选择并应用合适的优惠策略。
```csharp
static void Main(string[] args)
{
var cart = new ShoppingCart();
cart.AddProduct(new Product("牛奶", 10, 0.9)); // 添加商品
cart.AddProduct(new Product("面包", 5, 0.8));
var promotion = new FixedAmountDiscount(15); // 创建满20元减5元的策略
cart.ApplyPromotion(promotion);
Console.WriteLine($"购物车总额: {cart.TotalPrice}");
}
```
阅读全文