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.
Inheritance is tightly coupled whereas composition is loosely coupled.
Tight coupling means classes and objects are dependent on one another. In general, tight coupling is usually not good because it reduces the flexibility and re-usability of the code while Loose coupling means reducing the dependencies of a class that uses the different class directly.
Loose coupling is an approach to interconnecting the components in a system or network so that those components, also called elements, depend on each other to the least extent practicable. Coupling refers to the degree of direct knowledge that one element has of another.
Example 1: Imagine you have created two classes, A and B, in your program. Class A is called volume, and class B evaluates the volume of a cylinder. If you change class A volume, then you are not forced to change class B. This is called loose coupling in Java.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With