230 likes | 709 Views
Observer design pattern. A closer look at INotifyPropertyChanged , INotifyPropertyChanging and ObservableCollection. The observable design pattern. Observable An object that sends notifications to observers when something has happened to the object. Observer
E N D
Observer design pattern A closer look at INotifyPropertyChanged, INotifyPropertyChanging and ObservableCollection Observer design pattern
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 pattern
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 pattern
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 pattern
INotifyPropertyChang-ing • Interface INotifyPropertyChanging • One event • PropertyChangingEventHandler PropertyChanging • Notifies observers before a property changesits 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 pattern
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 pattern