[Design Pattern] Observer Pattern

[Design Pattern] Observer Pattern

Observer Pattern

ํ•œ ๊ฐ์ฒด์˜ ์ƒํƒœ๊ฐ€ ๋ณ€๊ฒฝ๋˜์—ˆ์„ ๋•Œ ๋‹ค๋ฅธ ๊ฐ์ฒด๋“ค์ด ์•Œ์•„์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ ์‚ฌ์šฉํ•œ๋‹ค.

์ƒํƒœ๋ฅผ ๊ฐ€์ง€๋Š” ๊ฐ์ฒด(Subject) / ์ƒํƒœ์˜ ๋ณ€๊ฒฝ์„ ๊ด€์ฐฐํ•˜๋Š” ๊ฐ์ฒด(Observer Object)
โžž 1:N ๊ด€๊ณ„

์žฅ์ 

  • Loose coupling
    subject์™€ observer๋Š” ์„œ๋กœ์˜ ์กด์žฌ๋ฅผ ์•Œ ํ•„์š”๊ฐ€ ์—†๋‹ค.

  • Scalability(ํ™•์žฅ์„ฑ)
    client-server ๊ตฌ์กฐ๋ณด๋‹ค ๋” ์ข‹์€ ํ™•์žฅ์„ฑ์„ ๊ฐ–๋Š”๋‹ค.

Java Observable / Observer

Observable

private boolean changed = false;
private Vector<Observer> obs; //Observable์€ ํ•˜๋‚˜ ์ด์ƒ์˜ Observer๋ฅผ ๊ฐ–๋Š”๋‹ค.

์ธ์Šคํ„ด์Šค๊ฐ€ ๋ณ€๊ฒฝ๋˜๋ฉด Observer์—๊ฒŒ ์•Œ๋ ค์ค€๋‹ค.

public void notifyObservers() {
    notifyObservers(null);
}

public void notifyObservers(Object arg) {
    Object[] arrLocal; //์ž„์‹œ ๋ฒ„ํผ, ํ˜„์žฌ Observer Vector์˜ ์Šค๋ƒ…์ƒท

    synchronized (this) {
        if (!changed)
        //(์ฃผ์˜) setChanged()๋ฅผ ํ†ตํ•ด changed๋ฅผ true๋กœ ๋ฐ”๊พธ์ง€ ์•Š์œผ๋ฉด notify๋„ ๋˜์ง€ ์•Š๋Š”๋‹ค.
            return;
        arrLocal = obs.toArray();
        clearChanged();
    }

    for (int i = arrLocal.length-1; i>=0; i--)
        ((Observer)arrLocal[i]).update(this, arg);
    }

Observer (interface)

Observable ๊ฐ์ฒด์˜ ๋ณ€ํ™”๋ฅผ ๊ด€์ฐฐํ•˜๋Š” Observer

void update(Observable o, Object arg);

Subject๊ฐ€ ๋ณ€๊ฒฝ๋˜๋ฉด ํ˜ธ์ถœ๋œ๋‹ค.
o: Observable ๊ฐ์ฒด
arg: Oservable์˜ notifyObservers()์—์„œ ์ „๋‹ฌ๋œ argument

Observer Pattern vs. Broadcast Receiver

์•ˆ๋“œ๋กœ์ด๋“œ ์•ฑ์ด ๋ณด๋‚ด๊ฑฐ๋‚˜ ๋ฐ›๋Š” Broadcast๋„ Observer ํŒจํ„ด๊ณผ ์œ ์‚ฌํ•˜๋‹ค.
ํ•˜์ง€๋งŒ Broadcast Receiver๋Š” Subject๋ฅผ ๋ชฐ๋ผ๋„ broadcast message๋ฅผ ๋ฐ›์•„ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค.

Observer Pattern vs. Event Listener

Observer์˜ update()

void update(Observable o, Object arg); // ๋ฐ์ดํ„ฐ๊ฐ€ Object๋กœ ์˜จ๋‹ค.

โžž Subject ๋ณ€๊ฒฝ ์‹œ ๋ฐ›๋Š” ๋ฐ์ดํ„ฐ๊ฐ€ ์—ฌ๋Ÿฌ ํƒ€์ž…์ด ์žˆ๋‹ค๋ฉด ๊ฐ๊ฐ์˜ ํƒ€์ž…์œผ๋กœ ๋ณ€ํ™˜ํ•ด์„œ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค.

์—ฌ๋Ÿฌ ํƒ€์ž…์˜ ๋ฐ์ดํ„ฐ๊ฐ€ ๋ณ€๊ฒฝ๋  ๊ฒฝ์šฐ๋ผ๋ฉด

Event Listener๋กœ ๊ตฌํ˜„ํ•˜๋Š” ๊ฒƒ์ด ๋ช…์‹œ์ ์ด๊ณ  ๊น”๋”ํ•˜๋‹ค!

Comments