This pattern is used when there is one to many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically.
- Subject: This is a class that contains a private collection of the observers that are subscribed to a subject for notification by using Notify operation.
- ConcreteSubject: 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.
- Observer: This is an interface which defines an operation Update, which is to be called when the subject’s state changes.
- ConcreteObserver: This is a class that implements 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)
public void Detach(IObserver o)
public void Notify()
foreach (IObserver o in observers)
<span style="color: #ff0000;">o.Update();</span>
public class ConcreteSubject : Subject
private string state;
public string GetState()
public void SetState(string newState)
state = newState;
<span style="color: #ff0000;">Notify();</span>
<span style="color: #ff0000;">public interface IObserver
public class ConcreteObserver : IObserver
private ConcreteSubject subject;
public ConcreteObserver(ConcreteSubject sub)
subject = sub;
public void Update()
string subjectState = <span style="color: #ff0000;">subject.GetState()</span>;
- ConcreteSubject (Account) notify to observers(Logger và Mailer, Security) when as there is an user Login.
- After receiving the notification and call
Update, ConcreteObserver (Logger và Mailer, Security ) use data from ConcreteSubject to get state to execute.
When to use it?
- Changes in 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.