Is a car with a subclass of a car bumper sticker suitable?

I am not an expert in OOPS and design patterns.

I came across this situation: is there a car with a subclass of a car bumper sticker?

If not, how can I add dynamic properties to an object instance? For example, a car, a car with a bumper sticker, etc.

Not all cars come with a bumper sticker. You can add a bumper sticker and even more than one bumper sticker. I can’t realize a sticker with a car, afayk, introducing me, will force me to add stickers. The bumper sticker on the car is one new property that appeared after the car (object?) Was created.

+5
source share
5 answers

You can use the Decorator design template for such cases. This will allow you to “add dynamic properties to the instance of the object” that you mentioned, you can add any stickers or any other property in all combinations, possibly “decorating” your class car.

+7
source

The changes in Car that you are talking about are dynamic attributes. Personally, I would implement a collection of accessories in the Car class, one of which would be the BumperSticker.

You can then add and remove accessories without subclassing Car for all available options.

, , BumperSticker Spoilers, , ++ .

+2

, (true/false) , .

, , , ? ( Java )

Dynamic, , ?

+1

.

class Car
{
public:
    bool hasBumperSticker() const { return m_hasBumperSticker; }

private:
    bool m_hasBumperSticker;
};

, :

class Car
{
public:
    bool hasBumperSticker() const { return m_bumperSticker != 0; }

private:
    BumperSticker* m_hasBumperSticker;
};
+1

Actually, when you buy a car, you yourself choose a car and a set of options (music, interior, etc.). As in real life, you can enter “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 its pros and cons, like any other.

0
source

All Articles