Vadim Pushtaev
Vadim Pushtaev

Reputation: 2353

Communication between object and its members

I have some deep question about OOP architecture.

What is a proper way to communicate between object and its members?

Let me explain what I mean by some examples. (I use C++, but it's not related to the question at all.)

class Shield
{
    int toughness;
    //...

    void broke();
};

class Human
{
    String name;
    int age;
    //...
    Shield my_shield;

    void scream();
    void equip_shield(Shield);
};

Human vadim;
Shield aegis;

vadim.equip_shield(aegis);
aegis.destroy();

So, now I want human to scream every time his or her shield is destroyed. But shield has no way to call its owner's method. He just doesn't know who is its owner.

One more example.

class Human
{
    //...
    void die();

};

class Crowd
{
    vector<Humans> people;
    //...
};

So, now I want crowd to tell all people to leave it if there are less than 10 people in the crowd. It's OK to crowd to tell such commands, but this check must be performed every time somebody dies in the crowd. So, again, human must somehow inform crowd that he or she is dead and ask crowd to recheck numbers of people in it.

The clear way to sort out this situation is to save the pointer to the crowd in every human. But it's dump way, because human can be in many crowds. Also there is synchronization problem here (same problem, actually, how can crowd know about the fact John left it?).

I believe that some trigger mechanism exists to solve such kinds of problems.

Thanks.

Upvotes: 2

Views: 154

Answers (1)

Dan
Dan

Reputation: 1888

What you are looking for is the observer pattern.

With the observer pattern the crowd would subscribe to the humans in the crowd and when a human emits the "death" status it can recheck the count.

Likewise for the shield that could fire a "shield broke" event that the human could recognize and start yelling.

Upvotes: 3

Related Questions