inheritanceumlassociationsclass-diagramclass-design

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


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


Solution

  • 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:

    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.