最近公司做了一个商城系统,分享一下购物车的设计。
public class ShopCart
{
private string UserId;
public List<CartItem> CartItems { get; set; } = new List<CartItem>();
private ShopCart()
{
}
public ShopCart(string userId)
{
this.UserId = userId;
InitCart();
}
#region 初始化购物车
private void InitCart()
{
CartItems = new ShopCarBll().GetListByUserId(UserId) ?? (List<CartItem>)new List<CartItem>();
}
#endregion
#region 对购物车进行操作
/// <summary>
/// 添加商品
/// </summary>
/// <param name="productId"></param>
/// <param name="count"></param>
/// <returns></returns>
public bool AddProduct(int productId, int count)
{
var productModel = new ProductBll().GetModel(productId);
if (productModel != null)
{
if (CartItems.Any(x => x.ProductId == productId))
{
return ModifyCount(productId, count);
}
else
{
//更新购物车到数据库中做持外化
if (new ShopCarBll().Add(UserId, productId, count))
{
CartItems.Add(new CartItem(productModel.Id, productModel.Price, count));
return true;
}
}
}
return false;
}
/// <summary>
/// 修改商品数量
/// </summary>
/// <param name="productId"></param>
/// <param name="count"></param>
/// <returns></returns>
public bool ModifyCount(int productId, int count)
{
var item = CartItems.FirstOrDefault(x => x.ProductId == productId);
if (item != null)
{
if (new ShopCarBll().Mobify(UserId, productId, count))
{
//更新到数据库中
item.Count = count;
return true;
}
}
return false;
}
/// <summary>
/// 移除商品
/// </summary>
/// <param name="productId"></param>
/// <returns></returns>
public bool RemoveProduct(int productId)
{
var item = CartItems.FirstOrDefault(x => x.ProductId == productId);
if (item != null)
{
if (new ShopCarBll().Remove(UserId, productId))
{
//更新到数据库中
CartItems.Remove(item);
return true;
}
}
return false;
}
#endregion
/// <summary>
/// 获取购物车总价
/// </summary>
/// <returns></returns>
public decimal GetSumFee()
{
return CartItems.Sum(x => x.Count * x.Count);
}
}
public class CartItem
{
public int ProductId { get; set; }
public int Count { get; set; }
public decimal Price { get; set; }
public CartItem(int productId, decimal price, int count)
{
this.ProductId = productId;
this.Count = count;
this.Price = price;
}
}
接着写测试类
public class testCart
{
public void Test()
{
string userId = "123123123";
ShopCart myCart = new ShopCart(userId);
myCart.AddProduct(1001, 1);
myCart.AddProduct(1002, 3);
myCart.AddProduct(1003, 2);
myCart.ModifyCount(1002, 5);//修改购物车数量
myCart.RemoveProduct(1003);//删除购物车商品
decimal sumFee = myCart.GetSumFee();//获取所有购物车金额
}
}
完工