03-DP-Observer.pdf
Document Details
Uploaded by EndorsedThermodynamics
PXL Hogeschool
Tags
Full Transcript
Design Patterns: Observer 43AON3150 Software Engineering Hogeschool PXL – Elfde-Liniestraat 24 – B-3500 Hasselt www.pxl.be - www.pxl.be/facebook Wheater Monitoring Station WeatherData Display System Current conditions Statistics Forecast … → this should be...
Design Patterns: Observer 43AON3150 Software Engineering Hogeschool PXL – Elfde-Liniestraat 24 – B-3500 Hasselt www.pxl.be - www.pxl.be/facebook Wheater Monitoring Station WeatherData Display System Current conditions Statistics Forecast … → this should be expandable! Design Prinicple 1 First draft Discussion We are coding to concrete implementations, not interfaces For every new display, we’ll need to alter this code We have no way to add (or remove) display elements at runtime The display elements don’t display a common interface We haven’t encapsulated the part that changes We are violating the encapsulation of the WeatherData class Publishers + Subscribers = Observer Newspaper analogy – A publisher starts publishing newspapers – You subscribe tot the service – You unsubscribe if you lose interest – Others can subscribe too (hotel, your neighbour, …) but they don’t know that from each other The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically. The Observer pattern The Observer pattern Design Principle 4 Strive for loosely coupled designs between objects that interact. Loose Coupling A Subject knows that an observer implements an interface, that’s all We can add observers at any time We never need to modify the Subject when adding new observers We can reuse subjects or observers independently Changes in subject does not affect observers and vice versa First Implementation Have I seen this before? Events (C#), Observable (Java) Whole new programming paradigm: RX – https://github.com/ReactiveX/RxJava – https://github.com/Reactive-Extensions/Rx.NET … Language integration Java – Observer, Observable – Push vs Pull style – Observable: setChanged: state has changed notifyObservers() or notifyObservers(Object arg) – Observer: update(Observable o, Object arg) – Critique pp. 71 Language integration C# – Events and delegates – http://stackoverflow.com/questions/1249517/super-simple-example- of-c-sharp-observer-observable-with-delegates