Consider this class diagram:
+--------+ * +------------------+ * afraid-of +------------+
| Garden |------>| Animal |<------------------------| Baby |
+--------+ +------------------+ +------------+
^
|
+----------+------+
| |
+------+------+ +------+-----+
| Cat | | Wolf |
+-------------+ +------------+
Animal has two roles:
- They will be walking around the garden (Class Instance)
- The baby is afraid of some animals (Class Type)
What baby should keep? One instance of each animal it’s afraid of? (sounds like poor design)
The type name? (I always try to avoid refactoring)
How should this be solved? (I’m using C# and I mention it only at the end because I hope there is a general, language-free design pattern or idea here)
Thanks
If babies are always afraid of the same animals, you don’t have to keep anything.
You can have a method:
If babies are afraid of different animals in different places and times, you should make every animal have a property AnimalType (flag enum). The baby will then have a property AfraidOf, of type AnimalType.
And then, checking if you are afraid of an animal is simple:
Finally, you should probably have different types of linking to different classes for different types of relationships in your schema (Contains, Inherits, Afraid of).