Circular dependency i przekazwyanie referencji do wskaźnika this

0

Cześć,

Mam problem zależności pomiędzy dwoma klasami, doczytałem, że najlepiej zrobić refactoring i wydzielić co wspólne do klasy trzeciej, ok. Natomiast będzie z tym więcej roboty niż zrobienie to w taki sposób jak chciałbym poniżej (być może mniej poprawny i niezalecany).
To co jest poniżej działa ale mam pytanie czy to co zrobiłem jest poprawne? Głównie chodzi o fragment przekazania referencji do wskaźnika this do metody hello.
Jeżeli nie, to w jaki sposób zrobić to poprawnie.

#ifndef FOO_H
#define	FOO_H

#include <iostream>
#include "Bar.h"

using namespace std;

class Bar;

class Foo {
public:

    void run() {
        bar->hello(*this);
    };

private:
    Bar *bar;

};

#endif	/* FOO_H */
#ifndef BAR_H
#define	BAR_H

#include <iostream>
#include "Foo.h"

using namespace std;

class Foo;

class Bar {
public:

    void hello(const Foo &foo) {
        cout << "hello Bar" << endl;
        ....
    }
    
};

#endif	/* BAR_H */
#include <iostream>
#include "src/cpp/Foo.h"

using namespace std;

int main(int argc, char** argv) {

    Foo foo;
    foo.run();

    return 0;
}
2

Działać będzie, ale od strony projektowej jest źle!
Takie rzeczy robi się tak (pomijając podział na pliki):

class IFoo;

class Foo {
public:
    explicit Foo(IFoo *observer):observer(observer){}
    void run() {
        observer->hello(this, "world");
    };
 
private:
    IFoo *observer;
};

class IFoo {
public:
     virtual void hello(Foo *, const std::string &) = 0;
};

class Bar : public SomeBase, public IFoo {
public:
    void hello(Foo *sender, const std::string &text) {
        cout << "hello " << text << endl;
    }
 
};

Bar bar;
Foo foo(&bar);
foo.run();

1 użytkowników online, w tym zalogowanych: 0, gości: 1