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:
등장 인물 ( 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 ) :
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, 또는 전혀 다른 종류의 객체가 호출 할 수도 있습니다.
패턴 사용법
패턴 사용의 장단점 ( 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.
관련 패턴들 :
추가 정보 :
출처 : http://sourcemaking.com/design_patterns/observer
Design Patterns : Element of Reusable Object Oriented Software ( by GoF, 1994 )
[디자인패턴] 메멘토 패턴 ( Memento Pattern ) (0) | 2015.11.03 |
---|---|
[디자인패턴] 인터프리터 패턴 ( Interpreter Pattern ) (0) | 2015.11.03 |
[디자인패턴] 중재자 패턴 ( Mediator Pattern ) (0) | 2015.11.03 |
[디자인패턴] 반복자(이터레이터) 패턴 ( Iterator Pattern ) (0) | 2015.11.03 |
[디자인패턴] 커맨드 패턴 ( Command Pattern ) (0) | 2015.11.03 |