K
Karthik V
I've been facing this situation often:
class NewFeature
{
TheClass *theClass;
NewFeature(TheClass *t) { theClass = t; }
void act() { // call methods on theClass }
}
class TheClass
{
NewFeature *feature; // More commonly, a list of NewFeature objects
AddFeature(NewFeature *f) { feature = f; // or append f to a list of
NewFeature objects }
}
In the above case, TheClass class contains pointers to NewFeature
objects, and each NewFeature object contains a pointer to the same
TheClass instance. This does seem to work most of the time but I'm not
comfortable with the idea of this circular reference.
Is there a standard design pattern to overcome this? The closest I saw
was visitor pattern. If I use that here, I'd do something like
class NewFeature
{
TheClass *theClass;
void accept(TheClass *t) { theClass = t; }
void act() { // call methods on theClass }
}
class TheClass
{
AddFeature(NewFeature *f) { f->accept(this); f->act(); }
}
But in this case, I'm losing the ability to keep track of the
NewFeature objects I have. Especially, if NewFeature.act() runs some
thread that calls TheClass methods later, I want TheClass to be able
to start / stop the thread when I want; so maintaining a list of those
pointers will be useful. If I do, I end up having my earlier code.
Please help!
class NewFeature
{
TheClass *theClass;
NewFeature(TheClass *t) { theClass = t; }
void act() { // call methods on theClass }
}
class TheClass
{
NewFeature *feature; // More commonly, a list of NewFeature objects
AddFeature(NewFeature *f) { feature = f; // or append f to a list of
NewFeature objects }
}
In the above case, TheClass class contains pointers to NewFeature
objects, and each NewFeature object contains a pointer to the same
TheClass instance. This does seem to work most of the time but I'm not
comfortable with the idea of this circular reference.
Is there a standard design pattern to overcome this? The closest I saw
was visitor pattern. If I use that here, I'd do something like
class NewFeature
{
TheClass *theClass;
void accept(TheClass *t) { theClass = t; }
void act() { // call methods on theClass }
}
class TheClass
{
AddFeature(NewFeature *f) { f->accept(this); f->act(); }
}
But in this case, I'm losing the ability to keep track of the
NewFeature objects I have. Especially, if NewFeature.act() runs some
thread that calls TheClass methods later, I want TheClass to be able
to start / stop the thread when I want; so maintaining a list of those
pointers will be useful. If I do, I end up having my earlier code.
Please help!