Observer Design Pattern falls under Behavioral Pattern of Gang of Four (GOF) Design Patterns in .Net. The command pattern is commonly used in the menu systems of many applications such as Editor, IDE, etc. In this article, I would like to share what is observer pattern and how is it work?
This pattern is used when there is one too many relationships between objects such as if one object is modified, its dependent objects are to be notified automatically.
Observer Design Pattern is allowed a single object, known as the subject, to publish changes to its state and other observer objects that depend upon the subject are automatically notified of any changes to the subject's state.
The UML class diagram for the implementation of the Observer Design Pattern is given below:
The classes, interfaces, and objects in the above UML class diagram are as follows:
This is a class that contains a private collection of the observers that are subscribed to a subject for notification by using Notify operation.
This is a class that maintains its own state. When a change is made to its state, the object calls the base class's Notify operation to indicate this to all of its observers.
This is an interface which defines an operation Update, which is to be called when the subject's state changes.
This is a class that implements the Observer interface and examines the subject to determine which information has changed.
public abstract class Subject { private ArrayList observers = new ArrayList(); public void Attach(IObserver o) { observers.Add(o); } public void Detach(IObserver o) { observers.Remove(o); } public void Notify() { foreach (IObserver o in observers) { o.Update(); } } } public class ConcreteSubject : Subject { private string state; public string GetState() { return state; } public void SetState(string newState) { state = newState; Notify(); } } public interface IObserver { void Update(); } public class ConcreteObserver : IObserver { private ConcreteSubject subject; public ConcreteObserver(ConcreteSubject sub) { subject = sub; } public void Update() { string subjectState = subject.GetState(); Console.WriteLine(subjectState); } }
Changes in the state of an object need to be notified to a set of dependent objects, not all of them.
Notification capability is required.
The object sending the notification does not need to know about the receivers objects.