On Jul 10, 12:39 pm, Chris Forone <4...@gmx.atwrote:
Bernd Strieder schrieb:
Chris Forone wrote:
is there a possibility to implement the decorator-pattern without
new/delete (nor smartpt)?
Why should new/delete be mandatory for the decorator pattern in C++?
in gof-book there is an example:
window->SetContents(
new BorderDecorator(
new ScrollDecorator(textView)
)
);
Border/ScrollDecorator are dyn. allocated...
In this particular case, they are both dynamically allocated;
the window is the only object which has a pointer to the
BorderDecorator, and the BorderDecorator is the only object
which has a pointer to the ScrollDecorator. Presumably, in this
particular case, they have established a convention that the
relevant classes are responsible for the delete (or they are
using the Boehm collector, but given when the book was written,
I doubt it).
In this particular case. There's no reason why it would always
be the case. In other cases, the objects involved may have
automatic lifetime, or be managed elsewhere. In many of my
decorators, I've found it useful to add a second parameter, a
bool deleteWhenFinished. If you pass it true, the decorator
does delete the decorated object in the destructor, if you pass
it false (which is the default), it doesn't. Garbage collection
would help here most of the time, but at least in one case, the
decorated objects use limited resources and require
deterministic destruction, so even with garbage collection, I'd
keep the flag and the (optional) delete.
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34