Observer design pattern A closer look at INotifyPropertyChanged, INotifyPropertyChanging and ObservableCollection Observer design pattern1
The observable design pattern Observable An object that sends notifications to observers when something has happened to the object. Observer An object that receives notification from observers. Aliases Notification = event, etc. Observer = listener = handler, etc. Observer design pattern2
Benefits of the Observer design pattern Observer – Observable is a many-to-many relationship An observable can observe any number of observers Including 0 An observer can observe any number of observables Normally 1 Observers are added and removed at runtime. Observer design pattern3
INotifyPropertyChang-ed The C# API has an interface INotifyPropertyChanged It has one event Event PropertyChangedHandler PropertyChanged Notifies observers when a property has changed its value Classes implementing this interface will be observable For example model classes Methods (observers) can be added to this event Methods (observers) will then be notified (called) AFTER something happens to the observable, and take appropriate action GUI can update Write to logs Write to files or databases, etc. Example: NotifyPropertyChangeSmallExample, including Unit test Observer design pattern4
INotifyPropertyChang-ing Interface INotifyPropertyChanging One event PropertyChangingEventHandler PropertyChanging Notifies observers before a property changes its value Classes implementing this interface will be observable For example model classes Method (observers) will then be notified (called) BEFORE something happens to the observable, and take appropriate action Throw an exception if the change is not legal according to some business rule Class invariant, etc. Example: NotifyPropertyChangeSmallExample Observer design pattern5
Support from ReSharper ReSharper (Visual Studio plugin) can help you implement INotifyPropertyChanged (NOT INotifyPropertyChanging) Class Student : INotifyPropertyChanged { } Click the light bulb in the left margin Chose “Implement INotifyPropertyChanged Property String Name { get; set } Click the light hammer in the left margin Chose “To property with change notification” Further readings resharper-7/ Observer design pattern6
ObservableCollection It’s a collection (like List) and it’s observable Implements the ICollection interface Notifies observers when elements are added or removed from the collection Not when the properties of individual members change Used in GUI applications Example ObservableCollectionExample Observer design pattern7