Підтримка
www.wikidata.uk-ua.nina.az
Div takozh Sposterigach znachennya Sposterigach Observer povedinkovij shablon proyektuvannya Takozh vidomij yak pidlegli Dependents vidavec peredplatnik Publisher Subscriber PriznachennyaViznachaye zalezhnist tipu odin do bagatoh mizh ob yektami takim chinom sho pri zmini stanu odnogo ob yekta vsih zalezhnih vid nogo spovishayut pro cyu podiyu PerevagiVin pidtrimuye princip vilnogo zv yazku mizh ob yektami yaki vzayemodiyut odin z odnim Dozvolyaye efektivno peredavati dani inshim ob yektam bez bud yakih zmin u klasah Subject abo Observer Sposterigachi mozhut buti dodani vidaleni v bud yakij moment chasuNedolikiInterfejs Observer povinen buti vprovadzhenij ConcreteObserver yakij peredbachaye uspadkuvannya Kompoziciyi dlya kompoziciyi nemaye oskilki interfejs Observer mozhe buti ekzemplyatorom Yaksho ce nepravilno realizovano sposterigach mozhe dodati skladnist i prizvesti do nenavmisnih problem iz produktivnistyu U programnomu zastosuvanni povidomlennya inodi mozhut buti nevibaglivimi i prizvesti do umov peregoniv abo neposlidovnosti UstrijPri realizaciyi shablonu sposterigach zazvichaj vikoristovuyutsya taki klasi Subject interfejs sho viznachaye metodi dlya dodavannya vidalennya ta opovishennya sposterigachiv Observer interfejs za dopomogoyu yakogo sposterezhuvanij ob yekt opovishaye sposterigachiv ConcreteSubject konkretnij klas yakij realizuye interfejs Subject ConcreteObserver konkretnij klas yakij realizuye interfejs Observer Pri zmini sposterezhuvanogo ob yektu opovishennya sposterigachiv mozhe buti realizovane za takimi scenariyami Sposterezhuvanij ob yekt nadsilaye kozhnomu iz zareyestrovanih sposterigachiv vsyu potencijno relevantnu informaciyu primusove rozpovsyudzhennya Sposterezhuvanij ob yekt nadsilaye kozhnomu iz zareyestrovanih sposterigachiv lishe povidomlennya pro te sho informaciya bula zminena a kozhen iz sposterigachiv za neobhidnosti samostijno zdijsnyuye zapit neobhidnoyi informaciyi u sposterezhuvanogo ob yekta rozpovsyudzhennya za zapitom Oblast zastosuvannyaShablon sposterigach zastosovuyetsya v tih vipadkah koli sistema volodiye takimi vlastivostyami isnuye yak minimum odin ob yekt sho rozsilaye povidomlennya ye ne menshe odnogo oderzhuvacha povidomlen prichomu yihnya kilkist i sklad mozhut zminyuvatisya pid chas roboti programi Cej shablon chasto zastosovuyut v situaciyah v yakih vidpravnika povidomlen ne cikavit sho roblyat oderzhuvachi z nadanoyu yim informaciyeyu Prostimi slovamiOb yekt volodiye vazhlivimi danimi i na nogo pidpisani sposterigachi Kozhen sposterigach maye mozhlivist obnoviti ci dani a inshi sposterigachi povinni otrimati pro ce spovishennya i obnovitis v slid yaksho ce neobhidno Sposterigach ne povinen zapituvati ob yekt z pevnoyu periodichnistyu vin zavzhdi znaye sho jogo dani aktualni Zv yazok iz inshimi paternamiPoserednik stvoryuye dvostoronnij zv yazok chasto nezminnij Zabiraye zalezhnosti mizh komponentami sistemi Komponenti stayut zalezhnimi vid poserednika Sposterigach stvoryuye odnostoronnij zv yazok yakij mozhe minyatis pid chas vikonannya programi Takim chinom odni ob yekti zalezhat vid inshih PrikladiJava Kod programi na movi Java package example pattern observer import java util ArrayList import java util List public interface Subject void attach Observer o void detach Observer o void notifyObserver public interface Observer void update public class ConcreteSubject implements Subject private List lt Observer gt observers new ArrayList lt Observer gt private int value public void setValue int value this value value notifyObserver public int getValue return value Override public void attach Observer o observers add o Override public void detach Observer o observers remove o Override public void notifyObserver for Observer o observers o update public class ConcreteObserver1 implements Observer private ConcreteSubject subject public ConcreteObserver1 ConcreteSubject subject this subject subject Override public void update System out println Observer1 subject getValue public class ConcreteObserver2 implements Observer private ConcreteSubject subject public ConcreteObserver2 ConcreteSubject subject this subject subject Override public void update String out for int i 0 i lt subject getValue i out System out println Observer2 out public class Program public static void main String args ConcreteSubject subject new ConcreteSubject ConcreteObserver1 observer1 new ConcreteObserver1 subject ConcreteObserver2 observer2 new ConcreteObserver2 subject subject attach observer1 subject attach observer2 subject setValue 3 subject setValue 8 PHP5 Kod programi na movi PHP5 lt php Interfejs za dopomogoyu yakogo sposterezhuvanij ob yekt spovishaye sposterigachiv interface Observer function notify obj Klas sposterezhuvanogo ob yekta class ExchangeRate static private instance NULL private observers array private exchange rate private function ExchangeRate static public function getInstance if self instance NULL self instance new ExchangeRate return self instance public function getExchangeRate return this gt exchange rate public function setExchangeRate new rate this gt exchange rate new rate this gt notifyObservers public function registerObserver obj this gt observers obj function notifyObservers foreach this gt observers as obj obj gt notify this Klas sposterigacha class ProductItem implements Observer public function construct ExchangeRate getInstance gt registerObserver this public function notify obj if obj instanceof ExchangeRate Update exchange rate data print Received update n Stvorennya ob yektiv sposterigachiv product1 new ProductItem product2 new ProductItem Zmina stanu sposterezhuvanogo ob yekta ta avtomatichne opovishennya pro ce sposterigachiv cherez funkciyu notify ExchangeRate getInstance gt setExchangeRate 4 5 gt C Kod programi na movi C using System using System Collections using System Threading namespace Observer lt summary gt Observer Pattern Judith Bishop Jan 2007 The Subject runs in a thread and changes its state independently At each change it notifies its Observers lt summary gt class Program static void Main string args Subject subject new Subject Observer Observer new Observer subject Center t t Observer observer2 new Observer subject Right t t t t subject Go Wait for user Console Read class Simulator IEnumerable string moves 5 3 1 6 7 public IEnumerator GetEnumerator foreach string element in moves yield return element class Subject public delegate void Callback string s public event Callback Notify Simulator simulator new Simulator const int speed 200 public string SubjectState get set public void Go new Thread new ThreadStart Run Start void Run foreach string s in simulator Console WriteLine Subject s SubjectState s Notify s Thread Sleep speed milliseconds interface IObserver void Update string state class Observer IObserver string name Subject subject string state string gap public Observer Subject subject string name string gap this subject subject this name name this gap gap subject Notify Update public void Update string subjectState state subjectState Console WriteLine gap name state Kod programi na movi C Rishennya na osnovi interfejsiv namespace ObserverPattern Interfaces interface IEvent interface IObserver lt in TEvent gt where TEvent IEvent void Handle object sender TEvent eventArgs interface ISubject lt TEvent gt where TEvent IEvent void Notify TEvent raisedEvent void Add IObserver lt TEvent gt observer void Remove IObserver lt TEvent gt observer class UserRenamedEvent IEvent public string Name get public UserRenamedEvent string name Name name class User ISubject lt UserRenamedEvent gt private string name public string Name get return name set name value this Notify new UserRenamedEvent value private readonly ICollection lt IObserver lt UserRenamedEvent gt gt userRenamedObservers new List lt IObserver lt UserRenamedEvent gt gt public void Add IObserver lt UserRenamedEvent gt observer userRenamedObservers Add observer public void Remove IObserver lt UserRenamedEvent gt observer userRenamedObservers Remove observer public void Notify UserRenamedEvent raisedEvent foreach var observer in userRenamedObservers observer Handle this raisedEvent class ConsoleLogger IObserver lt UserRenamedEvent gt public void Handle object sender UserRenamedEvent eventArgs Console WriteLine User has been renamed to eventArgs Name class Program static void Main string args var logger new ConsoleLogger var user new User user Add logger user Name John Doe Kod programi na movi C Rishennya na osnovi podij namespace ObserverPattern Events class UserRenamedEvent EventArgs public string Name get public UserRenamedEvent string name Name name class User private string name public string Name get return name set name value this OnUserRenamed new UserRenamedEvent value public event EventHandler lt UserRenamedEvent gt UserRenamedEvent keep this protected to override event in derived class protected void OnUserRenamed UserRenamedEvent raisedEvent UserRenamedEvent Invoke this raisedEvent class ConsoleLogger public void Handle object sender UserRenamedEvent eventArgs Console WriteLine User has been renamed to eventArgs Name class Program static void Main string args var logger new ConsoleLogger var user new User user UserRenamedEvent logger Handle user Name John Doe Kod programi na movi C Rishennya na osnovi servisu namespace ObserverPattern EventService interface IEvent interface IEventHandler lt in TEvent gt where TEvent IEvent void Handle object sender TEvent raisedEvent interface IEventService void Publish lt TEvent gt object sender TEvent raisedEvent where TEvent IEvent void Subscribe lt TEvent THandler gt where TEvent IEvent where THandler IEventHandler lt TEvent gt class EventService IEventService private readonly IDictionary lt Type List lt Type gt gt eventHandlers new Dictionary lt Type List lt Type gt gt public void Publish lt TEvent gt object sender TEvent raisedEvent where TEvent IEvent var eventType typeof TEvent if eventHandlers ContainsKey eventType return foreach var handlerType in eventHandlers eventType var handler Activator CreateInstance handlerType as IEventHandler lt TEvent gt handler Handle sender raisedEvent public void Subscribe lt TEvent THandler gt where TEvent IEvent where THandler IEventHandler lt TEvent gt var eventType typeof TEvent var handlerType typeof THandler if eventHandlers ContainsKey eventType eventHandlers Add eventType new List lt Type gt if eventHandlers eventType Any ht gt ht handlerType throw new ArgumentException Handler Type handlerType Name already is registered for eventType Name eventHandlers eventType Add handlerType public static EventService Instance get private EventService static EventService Instance new EventService class UserRenamedEvent IEvent public string Name get public UserRenamedEvent string name Name name class User private string name public string Name get return name set name value EventService Instance Publish this new UserRenamedEvent value class ConsoleLogger IEventHandler lt UserRenamedEvent gt public void Handle object sender UserRenamedEvent eventArgs Console WriteLine User has been renamed to eventArgs Name class Program static void Main string args EventService Instance Subscribe lt UserRenamedEvent ConsoleLogger gt var user new User user Name John Doe C Kod programi na movi C include lt iostream gt include lt string gt include lt map gt class SupervisedString class IObserver public virtual void handleEvent const SupervisedString amp 0 class SupervisedString Sposterezhnij klas std string str std map lt IObserver const IObserver const gt observers void Notify for auto amp iter observers iter second gt handleEvent this public void add IObserver amp ref observers insert item amp ref amp ref void remove IObserver amp ref observers erase amp ref const std string amp get const return str void reset std string str str str Notify class Reflector public IObserver Nadrukuvati sposterezhuvanij ryadok u std cout public virtual void handleEvent const SupervisedString amp ref std cout lt lt ref get lt lt std endl class Counter public IObserver Nadrukuvati dovzhinu sposterezhuvanogo ryadka v std cout virtual void handleEvent const SupervisedString amp ref std cout lt lt length lt lt ref get length lt lt std endl int main SupervisedString str Reflector refl Counter cnt str add refl str reset Hello World std cout lt lt std endl str remove refl str add cnt str reset World Hello std cout lt lt std endl return 0 ActionScript Kod programi na movi ActionScript fajl IObserver as package public interface IObserver function notify obj Object void fajl ExchangeRate as package public class ExchangeRate private static var instance ExchangeRate null private var observers Array private var exchangeRate Object public function ExchangeRate if instance null throw new Error Model Singleton public static function getInstance ExchangeRate if instance null instance new ExchangeRate return instance public function get exchangeRate Object return exchangeRate public function set exchangeRate value Object void exchangeRate value this notifyObservers public function registerObserver value IObserver void this observers push value private function notifyObservers void for each var observer IObserver in this observers observer notify this fajl ProductItem as package public class ProductItem implements IObserver public function ProductItem ExchangeRate getInstance registerObserver this public function notify value Object void if value is ExchangeRate var exchange ExchangeRate value as ExchangeRate trace exchange exchangeRate fajl Main as package import flash display Sprite public class Main extends Sprite public function Main void var item1 ProductItem new ProductItem var item2 ProductItem new ProductItem ExchangeRate getInstance exchangeRate 3 5 RealizaciyiShablon Sposterigach realizovanij v chislennih bibliotekah i sistemah vklyuchayuchi majzhe vsi instrumentariyi grafichnih interfejsiv koristuvacha Deyaki z najpomitnishih realizacij shablonu perelicheni nizhche ActionScript paket u ActionScript 3 0 yakij nasliduvav paket mx events u ActionScript 2 0 BASIC obgovorennya i realizaciya v C u GLib realizaciya ob yektiv i Callback v C Cya biblioteka chasto vklyuchena v inshi movi programuvannya C biblioteka shabloniv sigslot 14 bereznya 2010 u Wayback Machine C Signal Slot Library Cpp Events 24 lipnya 2010 u Wayback Machine Template based C implementation that introduces separation of connection management interface of the event object from the invocation interface XLObject 8 serpnya 2010 u Wayback Machine Template based C signal slot model patterned after Qt Signals 9 lipnya 2010 u Wayback Machine A lightweight and non intrusive C implementation libevent 23 travnya 2010 u Wayback Machine Multi threaded Crossplatform Signal Slot C Library an extension of the C STL providing a signal slot model The Qt C framework s C Exploring the Observer Design Pattern 7 bereznya 2010 u Wayback Machine the C and Visual Basic NET implementation using and the Event pattern Applying the Observer Pattern in NET Remoting using C Delphi a Delphi implementation Java The Java Swing library makes extensive use of the observer pattern for event management PerfectJPattern Open Source Project 29 lipnya 2010 u Wayback Machine Provides a context free and type safe implementation of the Observer Pattern in Java JavaScript a JavaScript core API based Signals and slots implementation an observer concept different from pretty lightweighted but still type safety enforcing Lisp Cells 17 lipnya 2011 u Wayback Machine a dataflow extension to Common Lisp that uses meta programming to hide some of the details of Observer pattern implementation PHP Event Dispatcher 28 bereznya 2010 u Wayback Machine a PHP implementation SPL 12 kvitnya 2011 u Wayback Machine the Standard PHP Library Python a Python implementation Observer Pattern using Weak References 16 travnya 2010 u Wayback Machine implementation by Michael Kent PyPubSub 16 travnya 2010 u Wayback Machine an in application Pub Sub library for Observer behavior NotificationFramework 6 lipnya 2010 u Wayback Machine classes directly implementing Observer patterns Ruby Observer 29 kvitnya 2010 u Wayback Machine from the Ruby Standard Library Also see Russ Olsen s coverage of this pattern in Ruby in Design Patterns in Ruby 11 lipnya 2010 u Wayback Machine Inshe CSP 13 chervnya 2010 u Wayback Machine Observer Pattern using CSP like Rendezvous each actor is a process communication is via rendezvous implements custom events through the observer pattern Implementation example of Observer or Publish Subscribe using G PosilannyaObserver Pattern implementation in JDK 6 6 serpnya 2009 u Wayback Machine Observer Pattern in Java 30 bereznya 2010 u Wayback Machine Definition C example amp UML diagram 23 lipnya 2010 u Wayback Machine J2EE Pattern Oriented Framework Observer Pattern recipe in Python 16 kvitnya 2010 u Wayback Machine DzherelaDesign Patterns Elements of Reusable Object Oriented Software 9 listopada 2012 u Wayback Machine LiteraturaAlan Shallouej Dzhejms R Trott Shablony proektirovaniya Novyj podhod k obektno orientirovannomu analizu i proektirovaniyu Design Patterns Explained A New Perspective on Object Oriented Design M Vilyams 2002 288 s ISBN 0 201 71594 5
Топ