为什么使用派生类来处理会话状态?

时间:2019-07-19 14:55:56

标签: c# asp.net-core software-design

我看到了一本实现购物车的书:

public class Cart 
{
   private List<CartLine> lineCollection = new List<CartLine>();
   public virtual void AddItem(Product product, int quantity){...}
   public virtual void RemoveLine(Product product){...}
}

public class CartLine {
   public int CartLineID { get; set; }
   public Product Product { get; set; }
   public int Quantity { get; set; }
}

和从SessionCart派生的Cart

//.GetJson() and .SetJson() are customized extension methods of ISession to serialize and deserialize objects.
public class SessionCart: Cart
{
   public static Cart GetCart(IServiceProvider services) {
      ISession session = services.GetRequiredService<IHttpContextAccessor>()?.HttpContext.Session;
      SessionCart cart = session?.GetJson<SessionCart>("Cart") ?? new SessionCart();
      cart.Session = session;
      return cart;
   }

   [JsonIgnore]
   public ISession Session { get; set; }

   public override void AddItem(Product product, int quantity) 
   {
       base.AddItem(product, quantity);
       Session.SetJson("Cart", this);
   }

   public override void RemoveLine(Product product)
   {
       base.RemoveLine(product);
       Session.SetJson("Cart", this);
   }
}

我很困惑,对我而言,SessionCart处理会话对象,难道我们不能将所有与会话相关的代码都移到Cart类吗,所以我们不需要SessionCart类吗?

0 个答案:

没有答案