Is the following a good design pattern in C++?
Pet PetOwner
| |
--------- --------------
| | | |
Cat Dog CatOwner DogOwner
In other words, two accompanying class hierarchies. Have you seen this done, and is it considered a good practice?
Let me clarify further. This design certainly follows the “open-closed” principle. It is “open” in the sense that new things can be added easily (new Horse and HorseOwner subclasses), and it is “closed” in the sense that new things can be added without modifying existing code.
The purpose of these two accompanying hierarchies is that, for example, PetOwner has a feed() virtual function, and Pet has a make_hungry_sound() virtual function. Also, Cat is constructed with a particular CatOwner.
Is there a better design pattern that can replace two related hierarchies like these? The reason I’m asking is that I’m wondering whether it’s considered a good practice to require people to add two classes at the same time when extending things. Seems a bit dubious…
Seems like a highly subjective question. Answers can be many (and more if you add more info to the question) so I’ll just comment based on what’s available in the question:
Assuming the
PetOwnerhas more to do than justfeed(), yes, it’s justified to have it. E.g. you won’t breed every pet, you won’t put every pet in a beauty contest.If all
PetOwnerhas to do is feed, just one concrete class is enough.