C# Observer Design Pattern

C# Observer Design Pattern

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!

 

 

 

 

C# Adapter Design Pattern

C# Adapter Design Pattern

Next pattern on my list is called adapter. This is another type of structural pattern. Adapter is the object which lets two mutually incompatible interfaces communicate with each other. Adapter pattern acts as a bridge between two incompatible interfaces. This pattern involves a single class called adapter which is responsible for communication between two independent or incompatible interfaces.

 

248-goravel-uk-swiss-switzerland-adapter-plugMost popular example that illustrate this problem is electrical socket adapter plug that changes. For example UK is using different sockets than rest of EU. That’s forcing people to use adapters.

 

 

To demonstrate this pattern I’ll use simplified example of game mechanics that have Interface of enemies, but one of the enemies is different than others and don’t have implementation of Attack method.  Instead this specific enemy is casting spells.

UML diagram

l

 

Lest begin by crating SpecialEnemy class that’s using CastSpell method. That is called Adaptee and will be used later in Adapter Class.

class SpecialEnemy
{
  public string CastSpell()
  {
     return "using spell";
  }
}

I will use return string to simplify the process.

Next lest create Interface IEnemy for managing the enemies behaviour, in this case it’s only one method for Attack.

interface IEnemy
{
  string Attack();
}

Now we need to inherit this interface by EnemyAdapter Class that will connect both pieces together.

class EnemyAdapter: IEnemy
{
  SpecialEnemy e = new SpecialEnemy();
  public string Attack()
  {
     return e.CastSpell();
  }
}

We need to add reference to the Adaptee in order to have access to CastSpell method. This way we can use the Attack Method without implementation it SpecialEnemy Adaptee.

Last step is to call the Enemy Attack method in client Class.

class Program
{
  static void Main(string[] args)
  {
    IEnemy enemy = new EnemyAdapter();
    Console.WriteLine(enemy.Attack());
    Console.ReadLine();
  }
}

As an output we get “using spell” string displayed.

This example was oversimplified, but it demonstrates the idea behind this simple pattern. I hope you will find it useful. In next article I’ll demonstrate another exciting creational Pattern called Builder. Stay Awesome!

C# Properties

C# Properties

This subject is related to encapsulation principle, you can find more about it here.

Properties are an extension of fields and are accessed using the same syntax. They use accessors through which the values of the private fields can be read, written or manipulated. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

Accessors

There are two basic types of accessors

set {accessor-body}
get {accessor-body}

Set allows to assign value to the field, called write method. It uses variable key word that represents the value that is assigned.

Get allows to return the value of the field, read method. Get must  return a value;

Field

Private field will prevent user from changing the data directly. This is concept of encapsulation. Field naming convention is to use underscore as prefix and start with low case letter.

 

public class MyClass
{
    // this is a field.  It is private to your class and stores the actual data.
    private string _myField;

    // this is a property.  When you access it uses the underlying field, but only exposes
    // the contract that will not be affected by the underlying field
    public string MyProperty
    {
        get
        {
            return _myField;
        }
        set
        {
            _myField = value;
        }
    }
}

 

Properties can be self implemented using

    public int Number{ get; set; }

 

Properties Implementation

One of properties advantages is option of selecting which of read/write method will be available,  for example we can want to restrict access to variable, making it read only. This will not allow user to change the data. To do this we write only get method in implementation.

Another advantage of properties is ability to perform operations on data inside the accessors. Let’s say we want to assign only positive numbers

using System;

class Example
{
    int _id;
    public int Id
    {
	get
	{
          return this._id;
        }
         set
	    // We don't allow this to be a negative value
	    if (value < 0 )
	    {
		throw new Exception("Invalid number");
	    }
	    this._id = value;
	}
    }
}

 

Default Values

Automatic properties have support for default values much like fields.

  public int Id { get; set; } = 404; // Has default value.

 

To conclude, Using properties is a vary good habit. It can protect the fields from corruption by setting checks conditions in setter. Or it can help with reading the value, using getter implementation. Using properties we can change the values of private field without exposing it, which is part of encapsulation principle. In next articles I’ll cover  most important design patterns. Stay Awesome!

 

 

Welcome

First of all, little bit about myself. I’m self taught software developer. My main language is c# and for my projects im using mainly .NET framework and Unity Engine.

Short biography. After doping out from University(Undergraduate in robotics) and over year of searching for place for myself I decided to go back to Software Development. I graduated from college in UK , after seeing the level of education here I decided to become a developer without help of university. I’ll share with you knowledge i gained over years of searching and self development, finishing lots of Massive Open Online Courses, education in different countries and  on different levels.

This blog is about software development and technology. I’ll post helpful tips and information that can be useful for software developers, game developers, and people  interested in technology. I’ll try to cover basic and more advanced topics.