Re: Collections of derived objects
Olivier Scalbert <olivier.scalbert@algosyn.com> wrote:
Let's say I have a base class Event and some sub classes EventType1,
EventType2, ...
1)
I would like to have a collection (vector or list for example) of a mix
of EventType1, EventType2, ...
I think I have to create a vector<Event*> and starts playing with "new".
And of course, I will forget the "delete" !
Are there any other options, to keep the code clean ?
I agree with Marcel's answer on this one. Use a smart pointer. If events
are immutable, you might also consider the flyweight pattern.
In the Flyweight, a factory keeps tabs on every possible event object
(conceptually at least, it can create them on demand,) and that way you
don't have to worry about deleting them. I stress though that this
pattern only works well if your Event objects are immutable.
2)
I would like to transform (serialize in string or something else) these
events (contained into a collection). As I will have different
transformations, I do not want to put the serialization code inside the
events, to not pollute them. How can I do that, in a clean way ? Visitor
pattern or something like that?
The bridge pattern is what you are looking for here. It's basically two
strategy patterns:
[Event]--------------->[Serializer]
A A
| |
+----+----+ +-------+------+
| | | |
[EventA] [EventB] [SerializerA] [SerializerB]