Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loose coupling in composition [closed]

Tags:

c++

oop

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.

like image 275
Fr0stBit Avatar asked Aug 16 '13 15:08

Fr0stBit


People also ask

Is composition loosely coupled?

Inheritance is tightly coupled whereas composition is loosely coupled.

What is the difference between close coupling and loose coupling?

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.

What is loosely coupled components?

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.

What is loose coupling with example?

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.


1 Answers

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.

like image 81
pillingworth Avatar answered Nov 16 '22 09:11

pillingworth