maximus
maximus

Reputation: 4302

How to notify all children object from parent object?

Lets say I have a Parent Object, and I have several Children objects. If one children does some special action, I want to notify all other childrens about it. How should I do it? Should I store all children in some array or are there any other more convenient approaches?

Upvotes: 0

Views: 784

Answers (2)

Petr Shypila
Petr Shypila

Reputation: 1499

In your case Parent object is Observable and children objects is Observers

Object which does some special action must implement Observable interface:

public interface Observable {
    void addObserver(Observer o);
    void removebserver(Observer o);
    void notifyObservers();
}

Concrete Observable class must also have array of observers(here children objects). So children objects must implement simple Observer interface.

public interface Observer {
    void update(/*data which you need to update in your children objects*/);
}

Later you need to register all your children objects to array of Observers in parent object using Observable.addObserver(Observer o); method. And after you can send them information using Observable.notifyObservers() method.

Also look it on Wikipedia!

Upvotes: 5

Juned Ahsan
Juned Ahsan

Reputation: 68715

User observer pattern, learn more about it from here:

http://en.wikipedia.org/wiki/Observer_pattern

Upvotes: 2

Related Questions