I am not an expert in OOPS and or design patterns.
I have come across this situation: Is a car with a bumper sticker subclass of a car?
If not then how can I add dynamic properties to instance of an object? For example a car, a car with bumper sticker etc.
Not all cars come with a bumper sticker. One can add a bumper sticker and even more than one bumper sticker. I can not implement a sticker with car, afaik, implementing me will force me to add stickers. A bumper sticker on a car is one new property that came into existence after car (object?) was created.
bumper sticker in American English noun. an adhesive-backed strip of paper for sticking onto the rear bumper of an automobile, usually bearing a tourist advertisement, slogan, joke, etc.
(NYSE: KMX) found that the number one reason people display bumper stickers, decals or magnets on their cars is to make a statement about themselves, their values and interests. Of the respondents who had not displayed a sticker, nearly a quarter said it's because they hadn't found one that represents them.
Sixty percent of car owners have put on a bumper sticker.
You can use the Decorator Design Pattern for cases like this. It will allow you to "add dynamic properties to instance of an object" which is what you mentioned, you can add any amout of stickers or any other property, in all combinations possible by "decorating" your car
class.
The changes to Car you are talking about are dynamic attributes. Personally I would implement a collection of Accessories in the Car class, one of which would be a BumperSticker.
You can then add and remove Accessories without having to subclass Car for all the options available.
If you go down the inheritance route think about the situation when a car has a BumperSticker and Spoilers, you would have multiple inheritance which is frowned upon in C++ and not available in other languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With