Loose coupling in composition
c++, oop
Solution
You can decouple using interfaces.
Create an interface `F` that implements the `foo()` method and pass this into B. Let A implement `F`. Now b can call `foo()` on F without knowing or even caring it is implemented by A.
Problem
I need help understanding loose coupling. How does one design a class that uses composition to be loosely coupled, when a child object needs to communicate with their parent object? Let me give an example: We have this: ``` class A { private: B b; public: void foo(); }; ``` How does the B object call the function foo() from its container class A? The obvious answer is "just pass a pointer from A to the b", but this is tight coupling, and an inflexible design. Can you please give me a simple solution to this problem (in C++ or Java preferably) or provide design techniques that deal with these kinds of problems? My real life example comes from developing a game engine for a JRPG. I have this class: ``` class StateMachine { private: std::map<std::string, State*> states; State* curState; public: StateMachine(); ~StateMachine(); void Update(); void Render(); void ChangeCurState(const std::string& stateName); void AddState(const std::string& stateName, State* state); }; ``` In every game loop `Update()` of `StateMachine` is called, which calls the `Update()` function of `curState`. I want to make `curState` is able to call `ChangeCurState` from the `StateMachine` class, but with loose coupling.