How to Correctly Model this Polymorphic Association?
Given the following Entities:
Container
User Client InstitutionThe Container entity has an association to one or more parties through the property AssignedToParties.
Container.AssignedToParties can contain a mix of Users, Clients, and Institutions.
What is the recommened domain model for this relationship.
I had considered the following options:
1) Create separate properties for each type:
Container.AssignedToUsers
Container.AssignedToClients Container.AssignedToInstitutionsThis seems pretty inelegant, but does not require business logic to check the types or do any downcasting.
2) Create a common base class "Party" for User/Client/Institution
Container.AssignedToParties would then be a collection of Party entities. This seems like an akward solution since the Party base class wouldn't have any methods or properties. I'm also not sure I like the idea of adding 开发者_开发问答one more layer of inheritance here.
This solution, like #3, would require the system to check the types at runtime to make decisions and then downcast to either User/Client/Institution to process them.
3) Create a Marker Interface IContainerAssignable that User/Client/Institution implement
This would at least provide some type safety, but would require type checking and downcasting.
Right now, I'm leaning towards #3. It seems the simplest, but I've read in quit a few places that if your code is running logic that has to test for a given type and downcast that you probably have a bad design.
Any advice appreciated.
Based on your comment in response to my question, I would not have the assignment handled by the container at all. To use your example, a file doesn't know or care who's watching it.
Instead, I'd either have the watcher implement some method (or collection property) to start watching a container (and in that case, making them an IContainerWatcher or the like would make sense), or else have that watching functionality offloaded entirely into a service that's dedicated to maintaining the associations, like a publish/subscribe mechanism does. This is conceptually analogous to a many-to-many join table in a database schema.
精彩评论