티스토리 뷰

Java

Observer Pattern

techbard 2016.07.19 11:36



# 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.


댓글
댓글쓰기 폼
공지사항
Total
394,934
Today
5
Yesterday
28
«   2018/11   »
        1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30  
글 보관함