模型(父)包含多态模型(子)集合时的业务逻辑

Business Logic when Model (Parent) contains a collection of Polymorphic Models (Children)

在 MVVM 架构中,特别是模型层;当 Collection<BasicModelType> 被使用满 inherit/implement BasicModelType 的对象时;如何处理集合中 "Models" 的任何业务逻辑,而不必自己在 "Models" 中实现一部分业务逻辑? (假设 "as" 和 "is" 的使用是不允许的,因为它是糟糕的 OOP 实践)。

---如果以上内容不完全清楚,请在下面进一步解释。---

"Model" 表示只有属性的基本 class。

ViewModel 通过 XMLService 获取模型。

XML服务只是一个 class,它知道如何根据 XML 文档中的内容创建模型。 (这只是为了说明模型是如何创建的)

OutputService 是一个 class,它知道如何使用模型根据模型中的内容从软件创建输出。除了需要处理模型之外,它还有其他逻辑。

该模型包含其他 ChildrenModel 的集合。 ChildrenModels 是多态的,因为它们来自 BaseModel。拥有一个 BaseModel 是可取的,因为它允许将它们存储并作为一个连续的集合呈现给用户。下面的示例,抱歉,因为这是我能想到的最简单的示例。

Truck : Vehicle
    Name
    HasTrailer

Car : Vehicle
    Name
    HasSpoiler

OutputService 中定义的逻辑需要执行不同的操作,具体取决于给定模型集合中的 ChildModel 是卡车还是汽车。问题当然是,ChildCollection 是基础 class 类型 Vehicle。实际类型唯一已知的时间是在 ChildModel 对象的实例化期间(它是已知的,因为 XML 中的类型是特定的)。

是否有一种通用模式来处理 OutputService 如何将其任何功能应用于 ChildModel 集合。根据定义,它需要知道每个模型类型。

让 switch 语句检查类型(使用 as 或 is)似乎是完全错误的。

当然,一个解决方案是在实际的 ChildModel 中包含来自 "OutputService" 的逻辑;只是在 BaseClass 或接口中公开执行该逻辑的函数。然后任何 object/service/veiwmodel 都可以遍历列表调用所述函数以获得特定于模型的结果。但这不是在本质上拆分了业务逻辑吗? "concerns" 不是到处撒了吗?

如果您阅读 The MVVM Pattern

查看

The view is responsible for defining the structure, layout, and appearance of what the user sees on the screen. Ideally, the view is defined purely with XAML, with a limited code-behind that does not contain business logic.

型号

The model in MVVM is an implementation of the application's domain model that includes a data model along with business and validation logic. Examples of model objects include repositories, business objects, data transfer objects (DTOs), Plain Old CLR Objects (POCOs), and generated entity and proxy objects.

查看模型

The view model acts as an intermediary between the view and the model, and is responsible for handling the view logic. Typically, the view model interacts with the model by invoking methods in the model classes. The view model then provides data from the model in a form that the view can easily use. The view model retrieves data from the model and then makes the data available to the view, and may reformat the data in some way that makes it simpler for the view to handle. The view model also provides implementations of commands that a user of the application initiates in the view. For example, when a user clicks a button in the UI, that action can trigger a command in the view model. The view model may also be responsible for defining logical state changes that affect some aspect of the display in the view, such as an indication that some operation is pending.

从这里我们可以看出,您应该使用 child 类 拆分业务逻辑。根据 child 抽象创建输出的逻辑。如果您对 OOP 设计有疑问,请考虑哪个更易于维护。参见 SOLID (object-oriented design)