Multiple Observers monitor the state change of one object
The monitored class holds multiple Observer instances, and each Observer uses the methods of the Observer class to change the state.
Observer holds monitored class objects </ font>
Check with the following class structure
class | Explanation |
---|---|
Mediator.class | Objects monitored by each Observer class Store an instance of each Observer class in a List Instance added to List()If so, notify all Observers of the size of the List |
abstract Observer.class |
Hold a Mediator instance to be monitored Implement the methods used by Mediator |
ob1.class~ob2.class | Implement Observer |
user(Main.class) | Operation check |
Mediator.class
class Mediator{
List list = new ArrayList<Observer>();
void add(Observer obsvr){
list.add(obsvr);
notifyTo(list.size()); //NotifyTo when List is updated()Run
}
void notifyTo(int size){
Iterator it = list.iterator();
while(it.hasNext()){
Observer ob = (Observer) it.next();
ob.update(size); //Update of each Observer class stored in List()Notify using
}
}
}
abstract_Oberver.class
abstract class Observer{
Mediator mediator = null;
int mediatorListSize = 0;
Observer(Mediator med){this.mediator=med;}
void update(int size){
mediatorListSize=size;
System.out.println(
mediatorListSize+":"+mediator.list.size()
);
}
}
java:ob1.class_ob2.class
class ob1 extends Observer{ob1(Mediator med){super(med);}}
class ob2 extends Observer{ob2(Mediator med){super(med);}}
user(Main.class)
public static void main(String[] args){
Mediator md = new Mediator();
md.add(new ob1(md));
md.add(new ob2(md));
}
Recommended Posts