Home > Mobile >  Associate a user with an abstract class implementation based on their role
Associate a user with an abstract class implementation based on their role

Time:11-07

Let's suppose that we have a User class that is necessarily associated with a Role, which can be DogLover or CatLover.

We have another abstract class called Animal, which has two implementations, Dog and Cat.

The User has an attribute called pet that will be a Cat or a Dog, depending on the Role chosen.

How can I show this on the diagram?

enter image description here

I cannot relate the implementation of each Animal with the Role since the animal must be associated with the user

CodePudding user response:

In this design Role and Animal are covariant, because the Role specialisation express love for corresponding Animal specialisations. There is unfortunately no easy way to model this.

One way of designing this is to use pet:Animal and model it with an association. You have then two options:

  • simply define a constraint for User, that would require the pet type and the role type match. To facilitate this design, I'd even consider making the role's specialisation a template class, i.e. Lover<T:Animal>
  • or make the role association a derived association (its name should be preceded with / ). The derivation would be based on the real type of the pet. SO if the pet changes, the derivation could change as well.

A better way to design this would be to move the pet from the User to the Role. The user has no animal, but in his/her role of DogLover he/she could have Dog (or CatLover a Cat). You can then use association specialization to clearly show the covariance. Several techniques can be used for this purpose as shown in the enter image description here

This being said, in the real life, DogLover and CatLover are not necessarily incompatible, and one could even have a Dog for historical reasons while being a CatLover. Separating the concerns of ownership and preference, would be an even better design.

  • Related