作为一名开发人员,我试图让我的类更加模块化和可重用。我遇到问题的一个领域是当我设计一个类来处理实体框架实体时。
例如,我可能会创建一个购物车类,它的角色是充当产品、折扣和其他与结帐相关的东西的容器。它公开了获取购物车总数的方法,并执行一些与购物车可以做什么和不能做什么相关的业务规则。
我可能会创建一个“产品”的实体框架实体,并让我的购物车接受这个实体。无论这看起来多么方便,它都会对我正在使用购物车的项目中的 Product 类产生不必要的依赖。如果我想将该购物车重新用于另一个项目,则“产品”实体不一定是相同的。
我怎样才能优雅地将我的购物车类与实体框架分离,并且不会在未来引起架构问题?
我想创建一个接口 IProduct,它具有购物卡所需的相关属性和方法,然后使我的实体类成为 IProduct 的实例。
基本上,我正在寻找一种好的设计模式来将我的类与项目的本地域实体分离,无论它们可能采用什么形式......
这就是我最终的结果;T 是 IProduct 的通用购物车。然后我将我的实体框架实体设为 IProduct:
public interface IProduct
{
/// <summary>
/// Unique Identifier For the product.
/// </summary>
int Id { get; set; }
decimal Price { get; set; }
}
public interface IShoppingCart<T> where T : IProduct
{
/// <summary>
/// Returns the total of all the products without any modifiers.
/// </summary>
decimal SubTotal { get; }
/// <summary>
/// Returns a total of everything in the cart, including all applicable promotions.
/// </summary>
decimal Total { get; }
/// <summary>
/// Returns a total of the discounts for the applicable promotions in the cart.
/// </summary>
decimal TotalDiscount { get; }
/// <summary>
/// Returns a count of products in the cart.
/// </summary>
int ProductCount { get; }
/// <summary>
/// Returns a count of unique products in the cart.
/// </summary>
int UniqueProductCount { get; }
/// <summary>
/// Adds a product increasing the product count if there is already one in the cart.
/// </summary>
/// <param name="product">Product To Add</param>
void AddProduct(T product);
/// <summary>
/// Remove an instance of a product from the cart, return the product that was removed.
/// </summary>
/// <param name="id"></param>
/// <returns>Instance of T</returns>
void RemoveProduct(int id);
/// <summary>
/// Returns a list of the products in the cart.
/// </summary>
/// <returns></returns>
IList<T> ListProducts();
/// <summary>
/// Remove all products from the cart;
/// </summary>
void ClearAllProducts();
/// <summary>
/// Add a promotion strategy to the cart.
/// </summary>
/// <param name="promotion"></param>
void AddPromotion(IPromotion<T> promotion);
/// <summary>
/// Remove a promotion from the cart.
/// </summary>
/// <param name="promotion"></param>
void RemovePromotion(string key);
/// <summary>
/// Remove all promotions from the cart.
/// </summary>
void ClearAllPromotions();
/// <summary>
/// List all of the promotions currently in the cart.
/// </summary>
/// <returns></returns>
IList<IPromotion<T>> ListPromotions();
/// <summary>
/// Remove everything from the cart (promotions and all).
/// </summary>
void EmptyCart();
}