Agenda:

In this article, We are going to discuss Observer design Pattern. I have used C# as base language to implement and tried to keep discussion short and simple. Let us get started with terminologies.

Terminology:

  • Subject: Responsible to notify Observers with updated object state.
  • Observer: Recepients observing subject.

Introduction

Observer Pattern is a behavioral software design pattern and it is suitable for problems where a system component(Subject) need to broadcast information to other components(Observers) as soon as there is change in object state.
By the book,

A one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
It can be visualized as shown in image below:


Keypoints

  • Subject keeps a track of observers to be notified and can have any number of observers.
  • Observer can register/unregister anytime based upon interest of use.
  • It works as a Push-based notification system.
  • It is mostly implemented in synchronous way i.e. appropriate method invocation.
  • .Net framework provides Reactive extensions to implement observer pattern.

Hands-On

Subject

  1. class ScoreSubject : ISubject
  2. {
  3. IList<IObserver> listObservers = new List<IObserver>();
  4. private int score;
  5. public int Score { get { return score; }
  6. set {
  7. score = value;
  8. Notify();
  9. } }
  10. public void Register(IObserver observer) {
  11. listObservers.Add(observer);
  12. }
  13.  
  14. public void Unregister(IObserver observer) {
  15. listObservers.Remove(observer);
  16. }
  17.  
  18. public void Notify() {
  19. listObservers.ToList().ForEach((observer) =>
  20. {
  21. observer.ScoreUpdated(Score);
  22. });
  23. }
  24. }

Observer

  1. class INDObserver : IObserver
  2. {
  3. public void ScoreUpdated(int score) {
  4.  
  5. Console.WriteLine("Current Score : " + score);
  6. }
  7. }
  8.  
  9. class AUSObserver : IObserver
  10. {
  11. public void ScoreUpdated(int score)
  12. {
  13. Console.WriteLine("Current Score : " + score);
  14. }
  15. }

Client

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. ScoreSubject scoreSubject = new ScoreSubject();
  6.  
  7. IObserver indObserver = new INDObserver();
  8.  
  9. IObserver ausObserver = new AUSObserver();
  10.  
  11. scoreSubject.Register(indObserver);
  12. scoreSubject.Score = 10;
  13. scoreSubject.Register(ausObserver);
  14. scoreSubject.Score = 100;
  15. Console.ReadLine();
  16. }
  17. }

For full source code refer rgilotra

Conclusion:

In this article, we learnt how observer pattern decides the behavior of an object in scenarios where multiple objects are dependent on on object. Your feedbacks are welcome.

Good Bye 👋 !! until I write again. Code well, Cook good.