# IObserver.java
public interface IObserver {
public abstract void update(EventMaker em);
}
# EventMaker.java
import java.util.Iterator;
import java.util.Random;
import java.util.Vector;
public class EventMaker {
private Vector<IObserver> observers = new Vector<>();
private static int number;
private static Random r = new Random();
public EventMaker() {
}
public int getNumber() {
return EventMaker.number;
}
public void add(IObserver observer) {
observers.add(observer);
}
public void remove(IObserver observer) {
observers.remove(observer);
}
public void clear(IObserver observer) {
observers.clear();
}
public void notifyObservers() {
Iterator<IObserver> itr = observers.iterator();
generateNumber();
while (itr.hasNext()) {
IObserver ob = itr.next();
ob.update(this);
}
}
public static void generateNumber() {
EventMaker.number = r.nextInt(10);
}
}
# Observer01.java
public class Observer01 implements IObserver {
private int number;
@Override
public void update(EventMaker em) {
number = em.getNumber();
if (number > 0 && number % 2 == 0) {
System.out.println("[" + number + "] even.");
}
}
}
# Observer02.java
public class Observer02 implements IObserver {
private int number;
@Override
public void update(EventMaker em) {
number = em.getNumber();
if (number > 0 && number % 2 != 0) {
System.out.println("[" + number + "] odd.");
}
}
}
# Observer03.java
public class Observer03 implements IObserver {
private int number;
@Override
public void update(EventMaker em) {
number = em.getNumber();
if (number == 0) {
System.out.println("[" + number + "] zero.");
}
}
}
# Main.java
public class Main {
public static void main(String[] args) {
EventMaker eventMaker = new EventMaker();
Observer01 observer01 = new Observer01();
Observer02 observer02 = new Observer02();
Observer03 observer03 = new Observer03();
eventMaker.add(observer01);
eventMaker.add(observer02);
eventMaker.add(observer03);
for (int i = 0; i < 10; i++) {
eventMaker.notifyObservers();
}
}
}
# 결과
[3] odd.
[1] odd.
[8] even.
[8] even.
[2] even.
[4] even.
[6] even.
[7] odd.
[7] odd.
[0] zero.
댓글 영역