C# Observer Design Pattern

C# Observer Design Pattern

Advertisements

This is very popular behavioural pattern. As the name suggests, the Observer Pattern is a pattern where the important objects are “observed” or watched for changes. This pattern is useful when we want to pass message from one object(subject) to multiple objects(observers).  Observers are not related with each other, but every one of them needs to inherit from IObserver interface.

To demonstrate the implementation of the pattern I’ll use an example with Enemy Class sending message to Subscriber when health is changed. Message will be sent to UserInterface and DifferentUnit Classes.

UML diagram:

l2

 

 

First we need to create IObserver Interface that will be used as a base for Concrete Classes.

public interface IObserver
{
  void Update();
}

Simple as that. Next we need to write implementation of this Interface in  Concrete Classes.

public class UserInteface : IObserver
{
  public void Update()
  {
     Console.WriteLine("Interface Updated");
  }
}
public class DifferentUnit : IObserver
{
  public void Update()
  {
     Console.WriteLine("Relation Updated");
  }
}

In this example we don’t need any extra parameters, just implementation of an Update() method.

Now lets move our attention to Subject site.  Subject interface need methods for subscribing and unsubsribing Observers. And method for Notifing the Listeners about the cahnge.

interface IEnemy
{
  void Subscribe(IObserver observer);
  void Unsubscribe(IObserver observer);
  void Notify();
}

 

In Enemy class I’m using may techniques like Properties, Generic List, Lambda Expressin, click on links if you want to learn more about them.

Enemy class inherits from IEnemy interface. It contains generic list of Observers, using interface as an object allows you to store objects of any class that inherits form IObserver interface. Notify() is called whenever health value is changing. Subscribe and Unsubscribe methods are using methods from List library

public class Enemy : IEnemy
{
  private List<IObserver> observers = new List<IObserver>();
  private int _health=10;
  public int Health
  {
    get { return _health; }
    set
    {
      _health = value;
      Notify();
    }
  }

  public void Notify()
  {
     observers.ForEach(x => x.Update());
  }

  public void Subscribe(IObserver observer)
  {
     observers.Add(observer);
  }

  public void Unsubscribe(IObserver observer)
  {
     observers.Remove(observer);
  }
}

Last part of implementation contains Client Class that will be used to create instances of Enemy Class and to display the final output.

class Program
{
  static void Main(string[] args)
  {
  Enemy subject = new Enemy();

  IObserver observer1 = new UserInteface();
  subject.Subscribe(observer1);

  subject.Subscribe(new DifferentUnit());
  subject.Health++;
  Console.WriteLine("--------------------");
  subject.Unsubscribe(observer1);
  subject.Health--;
  Console.ReadLine();
  }
}

Here you can see that two Concrete Classes are added to the Observer List by calling subscription method. Changing health value causes Notify() method that prints the values to the console. Later I unsubscribe one item from Observer and I’m changing the value once again, this time by decrementing the health value.

To conclude, Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependants are notified and updated automatically.

Link to source code for this pattern.

In Unity Engine this massaging system can be created with List of Events. You can find how to build messaging system in Unity in my article here. In my next article You will learn how to implement another exciting design patter. Stay Awesome!

 

 

 

 

Author: indiedevart

Indie Games Developer

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s