관찰자패턴 (1)

Creational Patterns ( 생성 패턴 )

These design patterns provides way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case. 

생성패턴은 객체의 생성로직을 숨기고 new 명령어를 통하지 않고 객체를 생성하는 방법들을 제공한다. 이는 특정 상황에서 어떤 방법으로 객체를 생성해야할지를 결정하는데 있어서 유연성을 제공한다. 


 Structural Patterns ( 구조적 패턴 )

These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities. 

구조적 패턴들은 클래스와 객체의 구성에 관여한다.

 

 Behavioral Patterns ( 행위적 패턴 )

These design patterns are specifically concerned with communication between objects.

이 패턴들은 객체들 사이의 커뮤니케이션에 관심을 가진다.

 

오늘 살펴볼  Observer 패턴은 Behavioral 패턴에 속합니다. 

옵저버라고 하니까 10년전에 스타크래프트에서 나왔던 옵저버가 생각이 나네요. cloaking상태로 여기저기 맵을 뒤지고 다녔던 녀석이죠. HP는 어찌나 적은지 한방에 그냥 펑 터져서 죽어버리던 녀석이었죠 ㅎㅎ.

이 옵저버 패턴은 한 객체의 상태를 지켜보고 있다가 이 객체의 상태가 변경이 되면 이 객체의 상태에 의존적인 다른 객체들의 상태를 자동으로 업데이트할 수 있게끔 해주는 패턴이라고 합니다.  

아래에서 좀 더 자세히 알아보도록 하겠습니다.


Observer Pattern Structure

 




  

패턴의 목적 ( Intent ) :  

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

옵 저버 패턴의 목적은 하나의 객체에 여러개의 객체가 의존적인 경우에, 그 한 객체의 상태가 변경이 되면 이 객체에 의존적인 다른 여러개의 객체들이 notification을 받고 자동으로 자신들의 상태를 업데이트를 할 수 있도록 하기 위함입니다.


패턴이 나오게 된 동기 ( Motivation ) :

     

Both a spreadsheet object and bar chart object can depict information in the same application data object using different presentations. The spreadsheet and the bar chart don't know about each other, thereby letting you reuse only the one you need. But they behave as though they do. When the user changes the information in the spreadsheet, the bar chart reflects the changes immediately, and vice versa.





This behavior implies that the spreadsheet and bar chart are dependent on the data object and therefore should be notified of any change in its state. And there's no reason to limit the number of dependent objects to two; there may be any number of different user interfaces to the same data.  


The Observer pattern describes how to establish these relationships. The key objects in this pattern are subject and observer. A subject may have any number of dependent observers. All observers are notified whenever the subject undergoes a change in state. In response, each observer will query the subject to synchronize its state with the subject's state.  


This kind of interaction is also known as publish-subscribe. The subject is the publisher of notifications. It sends out these notifications without having to know who its observers are. Any number of observers can subscribe to receive notifications.  

 


유용성 ( Applicability ) :

 

Use the Observer pattern in any of the following situations:  

 

    • When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.
    • When a change to one object requires changing others, and you don't know how many objects need to be changed.
    • When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these objects tightly coupled.

 



등장 인물 ( Participants ) :


Subject

o knows its observers. Any number of Observer objects may observe a subject.

o provides an interface for attaching and detaching Observer objects.

Observer

o defines an updating interface for objects that should be notified of changes in a subject. 

ConcreteSubject ( 이하 CS ) 

o stores state of interest to ConcreteObserver objects. 

o sends a notification to its observers when its state changes.

ConcreteObserver ( 이하 CO ) 

o maintains a reference to a ConcreteSubject object.

o stores state that should stay consistent with the subject's.  

o implements the Observer updating interface to keep its state consistent with the subject's.

 

 

원리 ( Collaborations ) :  

  • ConcreteSubject notifies its observers whenever a change occurs that could make its observers' state inconsistent with its own.
    ConcreteSubject( 이하 CS )객체가 이 객체를 지켜보는 옵저버들에게 자신의 상태가 변경되었다는 것을 알려줍니다. 그러면 옵저버들은 이 상태를 저장합니다. CS객체가 자신의 상태변화를 알려줄 때마다 옵저버들 또한 상태정보를 업데이트 하게 되는 거죠.
  • After being informed of a change in the concrete subject, a ConcreteObserver object may query the subject for information. ConcreteObserver uses this information to reconcile its state with that of the subject.
    CS 가 보낸 상태정보가 변경되었다는 알림 메시지를 받은 ConcreteObserver( 이하 CO )는 CS의 상태정보를 얻기위해 getState()를 할 수 있습니다. CO는 이렇게 얻은 정보를 이용해서 CS 상태와 자신이 갖고 있는 상태정보를 동일하게 동기화시킵니다.

    The following interaction diagram illustrates the collaborations between a subject and two observers:

 


Note how the Observer object that initiates the change request postpones its update until it gets a notification from the subject. Notify is not always called by the subject. It can be called by an observer or by another kind of object entirely. 옵저버가 관찰중인 객체의 상태정보를 가지고 자신이 가지고 있는 상태정보를 업데이트하는 것은 notify가 이루어진 뒤입니다. 그리고 이 notify는 CS, CO, 또는 전혀 다른 종류의 객체가 호출 할 수도 있습니다.

 


패턴 사용법

    1. Differentiate between the core (or independent) functionality and the optional (or dependent) functionality.
    2. Model the independent functionality with a "subject" abstraction.
    3. Model the dependent functionality with an "observer" hierarchy.
    4. The Subject is coupled only to the Observer base class.
    5. The client configures the number and type of Observers.
    6. Observers register themselves with the Subject.
    7. The Subject broadcasts events to all registered Observers.
    8. The Subject may "push" information at the Observers, or, the Observers may "pull" the information they need from the Subject.

 


패턴 사용의 장단점 ( Consequences ):  


The Observer pattern lets you vary subjects and observers independently. You can reuse subjects without reusing their observers, and vice versa. It lets you add observers without modifying the subject or other observers.

Further benefits and liabilities of the Observer pattern include thefollowing:  


1. Abstract coupling between Subject and Observer. All a subject knows is that it has a list of observers, each conforming to the simple interface of the abstract Observer class.The subject doesn't know the concrete class of any observer. Thus the coupling between subjects and observers is abstract and minimal.

Because Subject and Observer aren't tightly coupled, they can belong to different layers of abstraction in a system. A lower-level subject can communicate and inform a higher-level observer, thereby keeping the system's layering intact. If Subject and Observer are lumped together, then the resulting object must either span two layers (and violate the layering), or it must be forced to live in one layer or the other (which might compromise the layering abstraction).  


2. Support for broadcast communication. Unlike an ordinary request, the notification that a subject sends needn't specify its receiver. The notification is broadcast automatically to all interested objects that subscribed to it. The subject doesn't care how many interested objects exist; its only responsibility is to notify its observers. This gives you the freedom to add and remove observers at any time. It's up to the observer to handle or ignore a notification.  


3. Unexpected updates. Because observers have no knowledge of each other's presence, they can be blind to the ultimate cost of changing the subject. A seemingly innocuous operation on the subject may cause a cascade of updates to observers and their dependent objects. Moreover, dependency criteria that aren't well-defined or maintained usually lead to spurious updates, which can be hard to track down.

This problem is aggravated by the fact that the simple update protocol provides no details on what changed in the subject. Without additional protocol to help observers discover what changed, they maybe forced to work hard to deduce the changes.




관련 패턴들 :  

    • Mediator : Byencapsulating complex update semantics, the ChangeManager acts asmediator between subjects and observers.
    • Singleton :The ChangeManager may use the Singleton pattern to make it uniqueand globally accessible.


추가 정보 :       

    • Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple senders and receivers, but with different trade-offs. Chain of Responsibility passes a sender request along a chain of potential receivers. Command normally specifies a sender-receiver connection with a subclass. Mediator has senders and receivers reference each other indirectly. Observer defines a very decoupled interface that allows for multiple receivers to be configured at run-time.
    • Mediator and Observer are competing patterns. The difference between them is that Observer distributes communication by introducing "observer" and "subject" objects, whereas a Mediator object encapsulates the communication between other objects. We've found it easier to make reusable Observers and Subjects than to make reusable Mediators.
    • On the other hand, Mediator can leverage Observer for dynamically registering colleagues and communicating with them.


 

 


 

출처 :  http://sourcemaking.com/design_patterns/observer

Design Patterns : Element of Reusable Object Oriented Software ( by GoF, 1994 )