2

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

Christophe
  • 68,716
  • 7
  • 72
  • 138
DonBege
  • 23
  • 3

1 Answers1

1

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 answers to this other question, for example:

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.

Christophe
  • 68,716
  • 7
  • 72
  • 138
  • In this diagram, the Role-Animal association is not abstract. For example, an instance of DogLover may have a link with a Dog, but also a link with a Cat through the Role-Animal association. I don't think this is OP's intention. – www.admiraalit.nl Nov 07 '22 at 12:25
  • @www.admiraalit.nl interesting remark. Setting the end name identical at both end should be an implicit redefinition and limit this (unless an explicit redefine is preferred: https://stackoverflow.com/a/63122039/3723423 ?). – Christophe Nov 07 '22 at 21:10