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开发者_Go百科. A bumper sticker on a car is one new property that came into existence after car (object?) was created.
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 the bumper sticker is a common thing in your case, you can set a boolean attribute (true/false) or a string if that's it in your case.
If the bumper sticker is complicated to be a class of it self, perhaps the Car should Implement the sticker? (I am referring to Implementation in Java here)
As for Dynamic, would a database table of properties relating to the car be acceptable?
Don't overcomplicate this.
class Car
{
public:
bool hasBumperSticker() const { return m_hasBumperSticker; }
private:
bool m_hasBumperSticker;
};
Or, if the bumper sticker has its own properties:
class Car
{
public:
bool hasBumperSticker() const { return m_bumperSticker != 0; }
private:
BumperSticker* m_hasBumperSticker;
};
Actually, when you buy a car you choose the car itself and a set of options (music, interior, etc). As in a real life you can introduce 'options' in your car class. In a simple case it looks like (C++):
class Car {
enum CarOptions {
Bumper,
...
};
...
int options() const { return m_options; }
void setOptions(int options) { m_options = options }
...
};
Car c;
c.setOptions(c.options() | Car::Bumper);
Of course, this solution has it's own pros and cons, as any other.
精彩评论