개발방법론

[디자인패턴] 옵저버(Observer) 패턴

IT꿈나무 2022. 11. 21. 16:04
반응형

옵저버 패턴의 정의

 - 객체의 상태변화를 관찰하는 관찰자들, 즉 옵저버들의 목록을 객체에 등록하여 상태 변화가 있을 때마다 메서드 등을 통해 객체가 직접 목록의 각 옵저버에게 통지하도록 하는 디자인 패턴이다. 주로 분산 이벤트 핸들링 시스템을 구현하는 데 사용된다. 발행/구독 모델로 알려져 있기도 하다.[1]

- 다시, 유튜브의 구독 알람을 예시로 옵저버 패턴을 이해 볼수 있다.[2]

 

옵저버 패턴의 구조

옵저버 패턴의 구현 Type A

* Subject 행위자

public interface Subject {
	public void registerObserver(Observer observer);
	public void unregisterObserver(Observer observer);
	public void notifyObservers(String msg);
}
import java.util.ArrayList;
import java.util.List;

public class YouTuber implements Subject {
	private List<Observer> subscriberList;
	
	public YouTuber() {
		subscriberList = new ArrayList<>();
	}
	
	@Override
	public void registerObserver(Observer observer) {
		subscriberList.add(observer);
	}

	@Override
	public void unregisterObserver(Observer observer) {
		subscriberList.remove(observer);
	}

	@Override
	public void notifyObservers(String msg) {
		for (Observer observer : subscriberList) {
			observer.notifySubscriber(msg);
		}
	}
}

* 구독자

public interface Observer {
	public void notifySubscriber(String msg);
}
public class SubscriberA implements Observer {

	@Override
	public void notifySubscriber(String msg) {
		System.out.println(this.getClass() + " : " + msg);
	}
}

public class SubscriberB implements Observer {

	@Override
	public void notifySubscriber(String msg) {
		System.out.println(this.getClass() + " : " + msg);
	}
}

*Main

public class Main {

	public static void main(String[] args) {
		YouTuber youTuber = new YouTuber();
		Observer subscriberA = new SubscriberA();
		Observer subscriberB = new SubscriberB();
		
		System.out.println("subscriberA 구독 등록");
		youTuber.registerObserver(subscriberA);
		System.out.println("subscriberB 구독 등록");
		youTuber.registerObserver(subscriberB);
		
		youTuber.notifyObservers("New Video Upload!");
	}
}

 

옵저버 패턴의 구현 Type B

- 자바에는 Observer와 Observable 클래스가 구현되어 있다.

public class Observable {
    private boolean changed = false;
    private Vector<Observer> obs;

    /** Construct an Observable with zero Observers. */

    public Observable() {
        obs = new Vector<>();
    }

    /**
     * Adds an observer to the set of observers for this object, provided
     * that it is not the same as some observer already in the set.
     * The order in which notifications will be delivered to multiple
     * observers is not specified. See the class comment.
     *
     * @param   o   an observer to be added.
     * @throws NullPointerException   if the parameter o is null.
     */
    public synchronized void addObserver(Observer o) {
        if (o == null)
            throw new NullPointerException();
        if (!obs.contains(o)) {
            obs.addElement(o);
        }
    }

    /**
     * Deletes an observer from the set of observers of this object.
     * Passing <CODE>null</CODE> to this method will have no effect.
     * @param   o   the observer to be deleted.
     */
    public synchronized void deleteObserver(Observer o) {
        obs.removeElement(o);
    }

    /**
     * If this object has changed, as indicated by the
     * <code>hasChanged</code> method, then notify all of its observers
     * and then call the <code>clearChanged</code> method to
     * indicate that this object has no longer changed.
     * <p>
     * Each observer has its <code>update</code> method called with two
     * arguments: this observable object and <code>null</code>. In other
     * words, this method is equivalent to:
     * <blockquote><tt>
     * notifyObservers(null)</tt></blockquote>
     *
     * @see     java.util.Observable#clearChanged()
     * @see     java.util.Observable#hasChanged()
     * @see     java.util.Observer#update(java.util.Observable, java.lang.Object)
     */
    public void notifyObservers() {
        notifyObservers(null);
    }

    /**
     * If this object has changed, as indicated by the
     * <code>hasChanged</code> method, then notify all of its observers
     * and then call the <code>clearChanged</code> method to indicate
     * that this object has no longer changed.
     * <p>
     * Each observer has its <code>update</code> method called with two
     * arguments: this observable object and the <code>arg</code> argument.
     *
     * @param   arg   any object.
     * @see     java.util.Observable#clearChanged()
     * @see     java.util.Observable#hasChanged()
     * @see     java.util.Observer#update(java.util.Observable, java.lang.Object)
     */
    public void notifyObservers(Object arg) {
        /*
         * a temporary array buffer, used as a snapshot of the state of
         * current Observers.
         */
        Object[] arrLocal;

        synchronized (this) {
            /* We don't want the Observer doing callbacks into
             * arbitrary code while holding its own Monitor.
             * The code where we extract each Observable from
             * the Vector and store the state of the Observer
             * needs synchronization, but notifying observers
             * does not (should not).  The worst result of any
             * potential race-condition here is that:
             * 1) a newly-added Observer will miss a
             *   notification in progress
             * 2) a recently unregistered Observer will be
             *   wrongly notified when it doesn't care
             */
            // Android-changed: Call out to hasChanged() to figure out if something changes.
            // Upstream code avoids calling the nonfinal hasChanged() from the synchronized block,
            // but that would break compatibility for apps that override that method.
            // if (!changed)
            if (!hasChanged())
                return;
            arrLocal = obs.toArray();
            clearChanged();
        }

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

    /**
     * Clears the observer list so that this object no longer has any observers.
     */
    public synchronized void deleteObservers() {
        obs.removeAllElements();
    }

    /**
     * Marks this <tt>Observable</tt> object as having been changed; the
     * <tt>hasChanged</tt> method will now return <tt>true</tt>.
     */
    protected synchronized void setChanged() {
        changed = true;
    }

    /**
     * Indicates that this object has no longer changed, or that it has
     * already notified all of its observers of its most recent change,
     * so that the <tt>hasChanged</tt> method will now return <tt>false</tt>.
     * This method is called automatically by the
     * <code>notifyObservers</code> methods.
     *
     * @see     java.util.Observable#notifyObservers()
     * @see     java.util.Observable#notifyObservers(java.lang.Object)
     */
    protected synchronized void clearChanged() {
        changed = false;
    }

    /**
     * Tests if this object has changed.
     *
     * @return  <code>true</code> if and only if the <code>setChanged</code>
     *          method has been called more recently than the
     *          <code>clearChanged</code> method on this object;
     *          <code>false</code> otherwise.
     * @see     java.util.Observable#clearChanged()
     * @see     java.util.Observable#setChanged()
     */
    public synchronized boolean hasChanged() {
        return changed;
    }

    /**
     * Returns the number of observers of this <tt>Observable</tt> object.
     *
     * @return  the number of observers of this object.
     */
    public synchronized int countObservers() {
        return obs.size();
    }
}
public interface Observer {
    /**
     * This method is called whenever the observed object is changed. An
     * application calls an <tt>Observable</tt> object's
     * <code>notifyObservers</code> method to have all the object's
     * observers notified of the change.
     *
     * @param   o     the observable object.
     * @param   arg   an argument passed to the <code>notifyObservers</code>
     *                 method.
     */
    void update(Observable o, Object arg);
}

*Observable

import java.util.Observable;

public class YouTuber extends Observable {
	
	public void notifyEvent(String msg) {
		setChanged(); //동기화를 위해 setChanged()를 실행해야지만 notifyObservers()가 실행됨
		notifyObservers(msg);
	}
}

*Observer

import java.util.Observable;
import java.util.Observer;

public class SubscriberA implements Observer {

	@Override
	public void update(Observable o, Object arg) {
		System.out.println(this.getClass() + " : " + arg);
	}
}

public class SubscriberB implements Observer {

	@Override
	public void update(Observable o, Object arg) {
		System.out.println(this.getClass() + " : " + arg);
	}
}

*Main

import java.util.Observer;

public class Main {

	public static void main(String[] args) {
		YouTuber youTuber = new YouTuber();
		Observer subscriberA = new SubscriberA();
		Observer subscriberB = new SubscriberB();
		
		System.out.println("subscriberA 구독 등록");
		youTuber.addObserver(subscriberA);
		System.out.println("subscriberB 구독 등록");
		youTuber.addObserver(subscriberB);
		
		youTuber.notifyEvent("New Video Upload!");
	}
}

 

참고자료:

[1] 위키백과, 옵서버 패턴, https://ko.wikipedia.org/wiki/옵서버_패턴

[2] 옵저버 패턴, https://sorjfkrh5078.tistory.com/140

 

 

반응형