C# Command Design Pattern

C# Command Design Pattern Tutorial

Advertisements

Link to Source Code

Command pattern allows you to store list of code that is executed many times or at a later time. It also gives you easy way to implement Undo() that can just have opposite effect or undo multiple command, if commands are stored in list. This pattern is supports encapsulation, which is always a good thing. It may look complicated, it involves multiple classes:

Receiver – that performs the Action associated with the request.

Invoker  –that asks the command to carry out the request

Command -this is an interface which specifies the Execute and/or Undo operation.

Client – creates instance of an invoker, command and receiver and connects them.

As usual I’ll be using example related to video games. In my example I created simulation where Enemy can enter the field on the battlefield that can Heal him or it can add a Buff. I have two types of enemies Goblin and dragon, just to demonstrate the example of multiple receivers. When enemy exits the field the opposite action is triggered.

 

UML Diagram

l7

Receiver

Lets start by creating interface for Enemies. Every enemy that implements this interface can either take damage, heal, and Turn Buff OFF and ON.


interface IEnemy
{
  string Damage();
  string Heal();
  string BuffON();
  string BuffOFF();
}

Each method will return a string with massage about current status.

Here is implementation of the interface in one of the Enemy Class. Second One is very similar and you can find it in source code.


class Goblin : IEnemy
{
  public string BuffOFF()
  {
    return "Goblin enters the field-Buff is ON";
  }

  public string BuffON()
  {
    return "Goblin exits the field-Buff is OFF";
  }

  public string Damage()
  {
    return "Goblin exits the field- takes damage";
  }

  public string Heal()
  {
     return "Goblin enters the field- heals";
  }

Command

This interface will specify how retriever will respond to execute()and undo() commands.

interface ICommand
{
  void Execute();
  void UnDo();
} 

implementation of this interface requires a instance of an IEnemy receiver, in class constructor we pass the receiver that will be manipulated by the command. Again I’m showing here just one of two Classes, because both are identical.


class Heal : ICommand
{
  IEnemy _receiver;
  // Constructor
  public Heal(IEnemy receiver)
  {
    _receiver = receiver;
  }

  public void Execute()
  {
    Console.WriteLine(_receiver.Heal());
  }
  public void UnDo()
  {
    Console.WriteLine(_receiver.Damage());
  }
}

 

Invoker

In my example i’m simulating situation when enemy enters the field on the map, that triggers the commands. In the invoker we pass instance of command that we want to execute.


class Field
{
  private ICommand _command;

  public void SetCommand(ICommand command)
  {
    this._command = command;
  }

  public void EnterField()
  {
  _command.Execute();
  }
  public void ExitField()
  {
  _command.UnDo();
  }
}

Client

This is the last part of the program that connect everything together. In this specific example I chose the situation when Enemy Goblin Enters the Field, what trigger the Heal command. After leaving the field Goblin Takes Damage.


static void Main()
{
  // Create receiver, command, and invoker
  IEnemy receiver = new Goblin();
  ICommand command = new Heal(receiver);
  Field invoker = new Field();

  // Set and execute command
  invoker.SetCommand(command);
  invoker.EnterField();
  invoker.ExitField();

  Console.ReadKey();
}

This was just a simple demonstration of the pattern, one way of extending the functionality of it is to store command in the generic list, this way we can undo multiple commands or execute command already executed in the past. I hope you like will find it useful. In my next article I’ll cover on of the last design patters. Stay Awesome!

C# Iterator Design Pattern

C# Iterator Design Pattern tutorial

Link To source Code

This article will demonstrate the idea behind the Iteration pattern and simple implementation of it. The idea of the iterator pattern is to take the responsibility of accessing and passing trough the objects of the collection and put it in the iterator object. In C# Iterator pattern can be implemented simply using IEnumerable interface. Implementation of IEnumerable interface allows you to syntax sugar like foreach loop. This leads to the topic of collections.

In this post i’ll cover in more depth how Iterator is implemented by compiler. The iterator object will maintain the state of the iteration, keeping track of the current item and having a way of identifying what elements are next to be iterated. The abstraction provided by the iterator pattern allows you to modify the collection implementation without making any changes outside of collection.

This time you will see generic example of implementation, this is because i want to focus on the pattern functionality instead of  using techniques you may not know.

UML diagram

l6

 

Let’s start by creating interface for IIterator. Iterator Interface defines an interface for accessing and traversing elements.

interface IIterator
{
  int FirstItem { get; }
  int NextItem { get; }
  int CurrentItem { get; }
  bool IsDone { get; }
}

This will simulate looping through the objects of collection.

Implementation of this interface will make the iteration process clearer.  Implementation of this patter can be more difficult to understand because each Class is referring to the next one. Iterator need to have a reference to the IAggregate to create instance of it in the constructor, and use it later for returning its values.

Return value is set to int in Aggregate for this example.

class Iterator : IIterator
{
  IAggregate aggregate = null;

  //We need an index to track the iteration process
  int currentIndex = 0;

  public Iterator(IAggregate newAggregate)
  {
    aggregate = newAggregate;
  }
  //Returns item with index 0
  public int FirstItem
  {
    get
    {
      currentIndex = 0;
      return aggregate[currentIndex];
    }
  }

  //Returns next item
  public int NextItem
  {
   get
   {
     currentIndex += 1;

     if (IsDone == false)
     {
       return aggregate[currentIndex];
     }
     else
     {
       return -1;
     }
    }
  }

  public int CurrentItem
  {
    get
    {
       return aggregate[currentIndex];
    }
  }
//This method will give us feedabck when iteration ended
  public bool IsDone
  {
     get
     {
       if (currentIndex < aggregate.Count)
       {
          return false;
       }
       return true;
     }
   }
 }

 

Next interface to create is IAggregate.  One of the methods will return IIterator interface object.

 interface IAggregate
 {
   IIterator GetIterator();
   //This will handle manipulation of objects in the array
   int this[int itemIndex] { set; get; }
   int Count { get; }
 }

Implementation of this interface in Aggregate Class will be used as a place to create a list of an object that we will iterate through.

class Aggregate : IAggregate
{
  //Here is why Iterator methods returns integers;
  List<int> values = null;

  public Aggregate()
  {
    values = new List<int>();
  }

  public IIterator GetIterator()
  {
    //Iterator constructor takes IAggregate as parameter
    return new Iterator(this);
  }

  public int this[int itemIndex]
  {
    get
    {
      if (itemIndex < values.Count)
       {
           return values[itemIndex];
       }
      else
      {
        return -1;
      }
    }
    set
    {
        values.Add(value);
    }
   }

   public int Count
   {
     get
     {
       return values.Count;
     }
   }
 }

 

Last step is to create a Client that will create instance of Aggregate Class and Use Iterator to loop throug collection items.

class Program
{
  static void Main(string[] args)
  {
    Aggregate aggr = new Aggregate();

    aggr[0] = 7;
    aggr[1] = 8;
    aggr[2] = 9;
    aggr[3] = 89;

  IIterator iter = aggr.GetIterator();
  //Loops until isDone==false
    for (int i = iter.FirstItem; iter.IsDone == false; i = iter.NextItem)
    {
       Console.WriteLine(i.ToString());
    }
  Console.ReadLine();
  }
}

To conclude, Iteration pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. In C# this can be handled just by implementing IEnumerable interface. I hope you learned something new today. In Next article I’ll cover one last design patterns. Stay Awesome!

PS: Thanks for all Up votes On Reddit.com! I can’t reply to  comments, because of shadow-ban 😀

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!

 

 

 

 

Strategy Pattern C#

Strategy Pattern C#

Strategy is a behavioural design pattern, It’s used when Class have different implementation of the method, depended on the context. Here is formal definition of the pattern:

 Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

In order to understand the concept you should be familiar with principles of object oriented programming. Family of algorithms have the same function but different ways to execute it.  Strategy pattern can select the way of implementing the method from possible options in run time. I’ll be more clear after demonstrating the example.

UML class diagram:

Strategy

 

 

 

 

 

 

To demonstrate the use of this pattern I will create Program Class that executes one of methods, depended on the context.

Strategy can be implemented as Abstract Class or Interface. In this example i will use abstract class. Just like this.

abstract class Strategy
{
  public abstract void AlgorithmInterface();
}

So now we need to crate implementations of this method.

Each class inherits from Abstract Class and provides different implementation that will print the name of the class to the console.

class ConcreteStrategyA : Strategy
{
  public override void AlgorithmInterface()
  {
     Console.WriteLine("ConcreteStrategyA");
  }
}

class ConcreteStrategyB : Strategy
{
  public override void AlgorithmInterface()
  {
      Console.WriteLine("ConcreteStrategyB");
  }
}

class ConcreteStrategyC : Strategy
{
  public override void AlgorithmInterface()
  {
     Console.WriteLine("ConcreteStrategyC");
  }
}

Now let’s create a context of this behaviour

class Context
{
  private Strategy _strategy;

  // Constructor
  public Context(Strategy strategy)
  {
     this._strategy = strategy;
  }

  public void ContextInterface()
  {
     _strategy.AlgorithmInterface();
  }
}

When we crate instance of this Class we pass the strategy implementation that will be selected. Last part of the program is the Program Class that will connect everything together.

class Program
{
  static void Main()
  {
    Context context;
    context = new Context(new ConcreteStrategyA());
    context.ContextInterface();

    context = new Context(new ConcreteStrategyB());
    context.ContextInterface();

    context = new Context(new ConcreteStrategyC());
    context.ContextInterface();
  }
}

Here we create three instances of the Context Class, each one with different implementation of the Strategy interface.

It was example of structural code that represent the bare bones implementation of this pattern. In next part I’ll use more practical examples of implementation. Stay Awesome!