【问题标题】:Correct way to share logic between Domain Model and View Model在域模型和视图模型之间共享逻辑的正确方法
【发布时间】:2016-10-31 15:10:54
【问题描述】:

我正在渲染一个随新 ViewModel() 提供的 Create.cshtml。在我提交表单之前,我想使用 Ajax 来计算价格。我的视图模型不知道如何计算,也不想复制该功能。这种行为基于封装存在于域模型中。

使用 Ajax,我想在完成表单本身之前(在创建域模型之前)调用控制器上的“计算”操作方法,该方法为用户提供总价格。

如何在不破坏封装的情况下实现此功能?

注意:在该过程的后期,DomainModel 将用于在购物篮/付款/处理之前进行计算。

public class DomainModel
{
 public int Id { get; set; }
 public int Quantity { get; set; }
 public decimal Price { get; set; }

 public decimal Calculate()
 {
  return Quantity*Price;
 }
}

public class ViewModel
{
  [Required]
  public int Id { get; set; }
  [Required]
  public int Quantity { get; set; }
  public decimal Price { get; set;
}

【问题讨论】:

  • 我与一位同事讨论了将Calculate() 放入基类中,使用参数而不是使用类自己的属性。基类可以被 Domain 和 View 模型继承,但是,这感觉不对。
  • 您可以将执行这些计算的职责委托给一个单独的类 (TotalCalculator),然后在 DomainModel 和 ViewModel 中使用该类的实例来进行计算。即使用组合而不是继承。
  • @AdaTheDev 你的方法和静态计算器有什么区别?在这种情况下拥有实例有什么好处?
  • 创建一个基类是否更合适,只使用 calculate() - 然后在两个实例中继承?

标签: asp.net-mvc-4 model-view-controller


【解决方案1】:

您可以利用接口扩展,然后让每个扩展实现一个特定的接口。例如:

public interface MyAwesomeInterface
{
    int Quantity { get; }
    decimal Price { get; }
}

然后:

public class DomainModel : MyAwesomeInterface

public class ViewModel : MyAwesomeInterface

最后:

public static class MyAwesomeInterfaceExtensions
{
    public static Calculate(this MyAwesomeInterface foo)
    {
        return foo.Quantity * foo.Price;
    }
}

【讨论】:

  • 这并没有引起我的注意,它比原来的基类方法要干净得多。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多