简体   繁体   中英

Appropriate design for multiple objects that return similar data

I'm working on the following scenario:

  • A View has several tabs. Each tab is represented by a separate class and contains a data grid.

  • The tabs can each return the set of items that the user has selected. These items are very similar, but each one has one or two additional properties that are specific to it.

  • The View Presenter has a method called SendItems which should get the items from the current active tab and call the appropriate backend service method (one method per different collection of items).

What is the appropriate design here? I have thought of two ways so far:

  • Since the Items are very similar, I could theoretically group all the properties into 1 Item class and then I can abstract the whole thing out by having a method called GetItems() which would return the collection. I can then use a delegate dictionary on the tab type to call the right back-end method.

  • I can have all the tabs derive from a base tab, store the list of tabs in the Presenter and hold the Current tab. On SendItems, make several conditions (one per type (if CurrentTab is TabA => MethodA(), etc..)) and then downcast to retrieve the correct data. Finally, call the appropriate back-end method.

I don't find either solution appealing (group separate properties into one class / downcasting) and was hoping there is a standard way of solving this type of problem.

I believe in your case, I would go mostly with option 2.

  1. Create a parent tab class and make your other tabs derive from it.
  2. Create a parent class for all of your items which has all of the shared properties in it. Specific item types for each tab can derive from the parent class to define their extra properties
  3. In the parent tab, keep a list of the selected items. The list should be a List. Child classes can get the items in this collection and rely on runtime casting to get more specific types. In your case, the cast will basically be a noop (depending on how you do it) so there aren't really any performance issues there.
  4. On the parent tab, make the SendItems method abstract so each child tab has to implement it themselves

This is close to your second option above, except for taking advantage of a little more polymorphism magic and avoiding your conditions in SendItems - if you have conditions like that, just offload the logic to the child classes instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM