티스토리 뷰
The observer pattern (sometimes known as publish/subscribe) is a design pattern used in computer programming to observe the state of an object in a program. It is related to the principle of implicit invocation.
This pattern is mainly used to implement a distributed event handling system. In some programming languages, the issues addressed by this pattern are handled in the native event handling syntax. This is a very interesting feature in terms of real-time deployment of applications.
The essence of this pattern is that one or more objects (called observers or listeners) are registered (or register themselves) to observe an event which may be raised by the observed object (the subject). (The object which may raise an event generally maintains a collection of the observers.)
The UML diagram below illustrates this structure:
Contents[hide] |
[edit] Participant classes
The participants of the pattern are detailed below. Member functions are listed with bullets.
[edit] Subject
This class provides an interface for attaching and detaching observers. Subject class also holds a private list of observers. Contains these functions:
- Attach - Adds a new observer to the list of observers observing the subject.
- Detach - Removes an observer from the list of observers observing the subject.
- Notify - Notifies each observer by calling the notify() function in the observer, when a change occurs.
[edit] ConcreteSubject
This class provides the state of interest to observers. It also sends a notification to all observers, by calling the Notify function in its super class (i.e, in the Subject class). Contains this function:
- GetState - Returns the state of the subject.
[edit] Observer
This class defines an updating interface for all observers, to receive update notification from the subject. The Observer class is used as an abstract class to implement concrete observers. Contains this function:
- Notify - An abstract function, to be overriden by concrete observers.
[edit] ConcreteObserver
This class maintains a reference with the ConcreteSubject, to receive the state of the subject when a notification is received. Contains this function:
- Notify - This is the overridden function in the concrete class. When this function is called by the subject, the ConcreteObserver calls the GetState function of the subject to update the information it has about the subject's state.
When the event is raised each observer receives a callback. This may be either a virtual function of the observer class (called 'notify()' on the diagram) or a function pointer (more generally a function object or "functor") passed as an argument to the listener registration method. The notify function may also be passed some parameters (generally information about the event that is occurring) which can be used by the observer.
Each concrete observer implements the notify function and as a consequence defines its own behavior when the notification occurs.
[edit] Typical usages
The typical usages of the observer pattern:
- Listening for an external event (such as a user action). See Event-driven programming.
- Listening for changes of the value of an object property.
- In a mailing list, where every time an event happens (a new product, a gathering, etc.) a message is sent to the people subscribed to the list.
The observer pattern is also very often associated with the model-view-controller (MVC) paradigm. In MVC, the observer pattern is used to create a loose coupling between the model and the view. Typically, a modification in the model triggers the notification of model observers which are actually the views.
[edit] C# Implementations
/* First create an two interfaces that will encapsulate the methods of a subject including:<br /> * ISubject --> interface for the subject<br /> * RegisterObserver(IObserver observer); used to register an observer to the subject's notification list<br /> * UnregisterObserver(IObserver observer); used to remove a registered observer from the subject's notification list<br /> * NotifyObservers(); used to notify the observers in the notification list of any change that occurred in the subject<br /> */
public interface ISubject { void RegisterObserver(IObserver observer); void UnregisterObserver(IObserver observer); void NotifyObservers(); }
/* IObserver --> interface for the server<br /> * Update(); called by the subject to update the observer of any change<br /> * The method parameters can be modified to fit certain criteria<br /> */
public interface IObserver { void Update(); }
// Subject --> class the implements the ISubject interface....
using System.Collections; public class Subject : ISubject { //use array list implementation for collection of observers ArrayList observers; //decoy item to use as counter int counter; //constructor public Subject() { observers = new ArrayList(); counter = 0; } public void RegisterObserver(IObserver observer) { //if list does not contain observer, add if(!observers.Contains(observer) { observers.Add(observer); } } public void UnregisterObserver(IObserver observer) { //if observer is in the list, remove if(observers.Contains(observer)) { observers.Remove(observer); } } public void NotifyObservers() { //call update method for every observer foreach(IObserver observer in observers) { observer.Update(); } } //use function to illustrate observer function //the subject will notify only when the counter value is divisible by 5 public void Operate() { for(counter = 0; counter < 26; counter++) { if(counter % 5 == 0) { NotifyObservers(); } } } }
// Observer --> Implements the IObserver
public class Observer :IObserver { //this will count the times the subject changed //evidenced by the number of times it notifies this observer int counter; public Observer() { counter = 0; } //counter is incremented with every notification public void Update() { counter += 1; } //a getter for counter public int Counter { get { return counter; } } }
//TESTER
using System; public class ObserverTester { [STAThread] public static void Main() { Subject mySubject = new Subject(); Observer myObserver1 = new Observer(); Observer myObserver2 = new Observer(); //register observers mySubject.RegisterObserver(myObserver1); mySubject.RegisterObserver(myObserver2); mySubject.Operate(); //both observers are expected to yield 5 as a result of 5 notifications Console.WriteLine("Observer 1 : {0} notifications.",myObserver1.Counter); Console.WriteLine("Observer 2 : {0} notifications.",myObserver2.Counter); } }
[edit] Pseudocode
This pseudocode, written in a Python-esque syntax, demonstrates the observer pattern.
class Listener: def __init__(self, name, subject): self.name = name subject.register(self) def notify(self, event): print self.name, "received event", event
class Subject: def __init__(self): self.listeners = [] def register(self, listener): self.listeners.append(listener) def unregister(self, listener): self.listeners.remove(listener) def notify_listeners(self, event): for listener in self.listeners: listener.notify(event)
subject = Subject() listenerA = Listener("<listener A>", subject) listenerB = Listener("<listener B>", subject) # the subject now has two listeners registered to it. subject.notify_listeners ("<event 1>") # outputs: # <listener A> received event <event 1> # <listener B> received event <event 1>
[edit] Implementations
Here is an example that takes keyboard input and treats the input line as an Event. The native method notifyObserver is then called, in order to notify all observers of the event's occurrence, in the form of an invocation of their 'update' methods - in our example, ResponseHandler.update(...). The file myapp.java contains a main() method that might be used in order to run the code.
/* File Name : EventSource.java */ package OBS; import java.util.Observable; //Observable is here import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class EventSource extends Observable implements Runnable { String response; public void run() { try { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); while( true ) { response = br.readLine(); setChanged(); notifyObservers( response ); } } catch (IOException e) { e.printStackTrace(); } } }
/* File Name: ResponseHandler.java */ package OBS; import java.util.Observable; import java.util.Observer; /* this is Event Handler */ public class ResponseHandler implements Observer { private String resp; public void update(Observable obj,Object arg) { if(arg instanceof String) { resp = (String) arg; System.out.println("\nReceived Response: "+ resp ); } } }
/* Filename : myapp.java */ /* This is main program */ package OBS; public class myapp { public static void main(String args[]) { System.out.println("Enter Text >"); EventSource evSrc = new EventSource(); ResponseHandler respHandler = new ResponseHandler(); evSrc.addObserver(respHandler); evSrc.run(); } }
The observer pattern is implemented in numerous programming libraries and systems, including almost all GUI toolkits.
Some of the most notable implementations of this pattern:
- Here is an implementation of observer pattern in Objective-C
- The Java Swing library makes extensive use of the observer pattern for event management
- Boost.Signals, an extension of the C++ STL providing a signal/slot model
- The Qt C++ framework's signal/slot model
- libsigc++ - the C++ signalling template library.
- sigslot - C++ Signal/Slot Library
- XLObject - Template-based C++ signal/slot model patterned after Qt.
- GLib - an implementation of objects and signals/callbacks in C. (This library has many bindings to other programming languages.)
- Exploring the Observer Design Pattern - the C Sharp (C#) and Visual Basic .NET implementation, using delegates and the Event pattern
- Using the Observer Pattern, a discussion and implementation in REALbasic
- flash.events, a package in ActionScript 3.0 (following from the mx.events package in ActionScript 2.0).
- CSP - Observer Pattern using CSP-like Rendezvous (each actor is a process, communication is via rendezvous).
- YUI Event utility implements custom events through the observer pattern
- Py-notify, a Python implementation
- Event_Dispatcher, a PHP implementation
[edit] See also
- Design Patterns, the book which gave rise to the study of design patterns in computer science
- Design pattern (computer science), a standard solution to common problems in software design
[edit] External links
- A sample implementation in .NET
- Observer Pattern in Java
- Observer Pattern implementation in JDK 1.4
- Using the Observer Pattern in .NET
- Definition & UML diagram
- A discussion of fine-grained observers
scope/Purpose | Creational | Structural | Behavioral |
---|---|---|---|
Class | Factory Method | Adapter | Interpreter |
Class | Template Method | ||
Object | Abstract Factory | Adapter | Chain of Responsibility |
Object | Factory | Bridge | Command |
Object | Builder | Composite | Iterator |
Object | Prototype | Decorator | Mediator |
Object | Singleton | Facade | Memento |
Object | Flyweight | Observer | |
Object | Proxy | State | |
Object | Strategy | ||
Object | Visitor |
'IT > 프로그래밍' 카테고리의 다른 글
Volatile [펌 www.debuglab.com] (0) | 2007.12.18 |
---|---|
가변인자(...) va_start, va_arg, va_end (0) | 2007.11.18 |
Java Guide - Abstraction and Interfaces (0) | 2007.07.31 |
Java Guide - Polymorphism (0) | 2007.07.31 |
Java Guide - Polymorphism (0) | 2007.07.31 |
- Total
- Today
- Yesterday
- 지루박멸연구센타
- 열정의 힘을 믿는다
- Le4rN TO Cr4cK
- 디버깅에관한모든것(DebugLab)
- sysinternals
- FoundStone
- hashtab
- 보안-coderant
- 디바이스드라이버 개발자 포럼
- dualpage.muz.ro
- osronline.com - 드라이버 관련 정보 사이트
- NtInternals - NativeAPI Refere…
- pcthreat - spyware 정보 제공
- rootkit.com - 루트킷 관련 정보
- www.ntinternals.net
- WINE CrossRef. - source.winehq…
- tuts4you
- hex-rays
- idapalace
- idefense
- immunityinc
- threatexpert
- hdp.null2root.org
- www.crackstore.com
- crackmes.de
- www.who.is
- www.cracklab.ru
- community.reverse-engineering.…
- video.reverse-engineering.net
- SnD
- 클레이 키위
- reversengineering.wordpress.co…
- www.openrce.org
- www.woodmann.com
- PEID.Plusins.BobSoft
- roxik.com/pictaps/
- regexlib.com
- spyware-browser.com
- www.usboffice.kr
- regulator
- www.txt2re.com
- ietab.mozdev.org
- zesrever.xstone.org
- www.heaventools.com/PE-file-he…
- www.heaventools.com
- www.innomp3.com
- 울지않는벌새
- exetools.com-forum
- exetools.com
- utf8 conv
- robtex - IP trace
- onsamehost - same IP sites
- JpopSuki
- jsunpack.jeek.org
- wepawet.iseclab.org
- www.jswiff.com
- www.hackeroo.com
- winesearcher.co.kr
- khpga.org
- malwareurl.com
- anubis.iseclab.org
- www.crummy.com-eautifulSoup
- malwarebytes.org/forums
- bbs.janmeng.com
- blackip.ustc.edu.cn
- eureka.cyber-ta.org
- exploit-db.com
- ElasticSearch
- 군함도
- 주택구매력지수
- 신한저축은행
- 사회간접자본
- 실시간트래이딩
- 맥쿼리인프라
- hai
- O365
- 미국주식
- CriticalSection
- PIR
- 주식
- 자동트래이딩
- ChatGPT
- 공공인프라
- ubuntu
- 시스템트래이딩
- systemd
- 매매가격지수
- 피봇
- ROA
- SBI저축은행
- 주식트래이딩
- Pivot
- 다올저축은행
- INVOICE
- 레고랜드
- logrotate
- 전세매매지수
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |