Observer

Frequency of Use
High

Intent
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Structure

20140608-185029-67829449.jpg

Applicability
Use the Observer pattern in any of the following situations:

  • When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.
  • When a change to one object requires changing others, and you don’t know how many objects need to be changed.
  • When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don’t want these objects tightly coupled.

 

Code Implementation (C#)

using System;
using System.Collections.Generic;

namespace Observer
{
 public class MainClass
 {
  public static void Main()
  {
    ConcreteSubject s = new ConcreteSubject();
    s.Attach(new ConcreteObserver(s, "X"));
    s.Attach(new ConcreteObserver(s, "Y"));
    s.Attach(new ConcreteObserver(s, "Z"));

    s.SubjectState = "ABCD";
    s.Notify();

    Console.ReadKey();
  }
 }

 abstract class Subject
 {
  private List<Observer> _observers = new List<Observer>();

  public void Attach(Observer observer)
  {
    _observers.Add(observer);
  }

  public void Detach(Observer observer)
  {
    _observers.Remove(observer);
  }

  public void Notify()
  {
   foreach (var observer in _observers)
   {
    observer.Update();
   }
  }
 }

 class ConcreteSubject : Subject
 {
  private string _subjectState;

  public string SubjectState
  {
    get { return _subjectState; }
    set { _subjectState = value; }
  }
 }

 abstract class Observer
 {
   public abstract void Update();
 }

 class ConcreteObserver : Observer
 {
   private string _name;
   private ConcreteSubject _subject;
   private string _observerState;

   public ConcreteObserver(ConcreteSubject subject, string name)
   {
     this._subject = subject;
     this._name = name;
   }

   public override void Update()
   {
    _observerState = _subject.SubjectState;
    Console.WriteLine("State of Observer {0} is {1}",
                      _name, _observerState);

   }

   public ConcreteSubject Subject
   {
    get { return _subject; }
    set { _subject = value; }
   }

  }
 }

Code Output

State of Observer X is ABCD 
State of Observer Y is ABCD 
State of Observer Z is ABCD
Advertisements
Categories: C#, Design Pattern, Programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: