C# Decorator Design Pattern

C# Decorator Design Pattern tutorial

Advertisements

Link to Source code

In this article You will learn how to implement decorator pattern in C#. Decorator pattern allows to modify an object dynamically it simplifies the code by adding new functionality at runtime. Adding new functionality to the object doesn’t effect the initial class structure.

In my example I’ll simulate the process of enchanting an item in RPG game.

UML Diagram:

l11

Component

This interface will be used as base for decorator and concrete items. It contains methods that will return properties of an item.

public interface IItem
{
    string GetName();
    int GetValue();
}

Base Items like armor or Sword will implement this interface and return fixed values.

class Sword : IItem
{
    public string GetName()
    {
        return "Iron Sword";
    }

    public int GetValue()
    {
        return 20;
    }
}

Decorator

This is the key part of the pattern, it maintains a reference to a Component object and defines an interface that conforms to Component’s interface. In my example this will be represented as an Enchantment of the item. Decorator will have form of abstract class and will have protected constructor

A protected member is accessible within its class and by derived class instances.

abstract class Enchantment : IItem
{
  IItem _item = null;

  protected int _Value = 0;

  protected Enchantment(IItem baseItem)
  {
    _item = baseItem;
  }

  public string GetName()
  {
    return (_item.GetName() +" +1 ");
  }

  public int GetValue()
  {
    return (_item.GetValue() + _Value);
  }
}

Class that extends the Decorator can change the protected values in parent to eventually change the return values.

class Magic : Enchantment
{
  public Magic(IItem baseComponent): base(baseComponent)
  {
    this._Value = 30;
  }
}

Client

Last part of an application. Here the instance of an item is created and modified. In this example you can see how the values changed after adding decorator.

class Program
{
  static void Main(string[] args)
  {
    IItem newItem = new Sword();
    Console.WriteLine(newItem.GetName() + " Value: " + newItem.GetValue().ToString());

    newItem = new Magic(newItem);
    Console.WriteLine(newItem.GetName() + " Value: " + newItem.GetValue().ToString());

    Console.ReadLine();
  }
}

To conclude, Decorator can attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for extending functionality. I hope that this was understandable and it will help you with your projects. This was probably the last design pattern to cover on my blog, last in this month at least. 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!

 

 

 

 

C# Builder Design Pattern

C# Builder Design Pattern

In this article you will learn how to implement builder design pattern. This is one of structural patterns. You can use it when you need to have control over how complex objects would be created at runtime. This pattern gives you step by step approach on the object creation process. This is useful if you want to reuse the same creation process to build different representations. I’ll demonstrate the implementation of the pattern on simplified  real word example. And I’ll explain it step by step.

To show you the pattern I created the system of creating two types of enemies, each process of creation takes multiple steps, that’s good opportunity for using builder.

UML diagram:

l1

 

  1. IEnemy – Builder interface
  2. EnemyTypeA and EnemyTypeB– Concrete Builder
  3. Enemy– Product
  4. EnemyCreator – Director

 

So first let’s create an enemy Class, we will instantiate objects of this class in Concrete Builders.

class Enemy
{
  public string model;
  public string behaviour;
  public string components;
}

Here we have three public variables just to  demonstrate the example.

Next we need Builder interface that will contains all the method that will be implemented by Enemies Classes. And we have Get Enemy method that will return the Enemy Class instance after competing the construction process.

interface IEnemy
{
  void SelectModel();
  void SelectBehaviour();
  void AddComponents();

  Enemy GetEnemy();
}

 

Next step is to create Classes based on the interface. Each class will have unique implementation of the interface methods.  In order to get access to Enemy Class properties we need to create instance of this Class.

class EnemyTypeA : IEnemy
{
  Enemy enemy = new Enemy();
  public void AddComponents()
  {
    enemy.components="Components Added";
  }

  public void SelectBehaviour()
  {
    enemy.behaviour= "Behaviour Type A Selected";
  }

  public void SelectModel()
  {
     enemy.model = "Body Type A Selected";
  }
  public Enemy GetEnemy()
  {
     return enemy;
  }
}
//EnemyTypeB
class EnemyTypeB : IEnemy
{
  Enemy enemy = new Enemy();
  public void AddComponents()
  {
     enemy.components = "Components Added";
  }

  public void SelectBehaviour()
  {
     enemy.behaviour = "Behaviour Type B Selected";
  }

  public void SelectModel()
  {
     enemy.model = "Body Type B Selected";
  }
  public Enemy GetEnemy()
  {
     return enemy;
  }
}

 

Now it’s time for creating Director that will contain the logic behind creating new enemy. In Class constructor we pass IEnemy interface, this way we can pass any Class that inhirates form this interface.

class EnemyCreator
{
  private readonly IEnemy enemyBuilder;

  public EnemyCreator( IEnemy enemyType)
  {
     enemyBuilder = enemyType;
  }
  public Enemy ConstructEnemy()
  {
    enemyBuilder.SelectBehaviour();
    enemyBuilder.SelectModel();
    enemyBuilder.AddComponents();

    return enemyBuilder.GetEnemy();
  }
}

Construct Enemy method return instance of Enemy Class with new properties.

Last thing to complete the implementation is to create Client Class that will  create instances of each enemy type.

class Program
{
  static void Main(string[] args)
  {
  var enemyCreator = new EnemyCreator(new EnemyTypeA());
  var enemy = enemyCreator.ConstructEnemy();
  enemy.ShowInfo();
  Console.WriteLine("_______________________");
  enemyCreator = new EnemyCreator(new EnemyTypeB());
  enemy = enemyCreator.ConstructEnemy();
  enemy.ShowInfo();
  Console.ReadLine();
  }
}

 

To conclude, Builder pattern Separates the construction of a complex object from its representation so that the same construction process can create different representations. I hope you found it useful and you will implement this pattern to you programs. I next article I’ll cover another exciting design patter. Stay Awesome!

Link To Full Source Code 

 

 

 

 

 

 

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# Facade Design Pattern

C# Facade Design Pattern tutorial

5964294206_8e1e34fe28_b

Facade is one of the most popular design patterns, you probably used it in your project without knowing it. This pattern is used to simplify the complex system into one interface. The facade design pattern is particularly used when a system is very complex or difficult to understand because system has a large number of interdependent classes or its source code is unavailable. You would use it if you have a complex system where the abstractions and the implementations of it are tightly coupled and you would not want the consumer to contact the complex system directly. This pattern involves a single wrapper class which contains a set of members which are required by client. These members access the system on behalf of the facade client and hide the implementation details.

I’ll demonstrate this on an example within a game where player interacts with enemy. Enemy Class contains two sub-classes Move and Speak, this is simplified example of course.

UML diagram:

Facade

 

 

 

 

 

 

 

 

 

 

 

 

 

Lets start with sub-classes. In this example I’m not passing any parameters into Facade.

First lets create Move Subclass that contains two methods each method returns a string.

internal class Move
{
  public string FindPlayer()
  {
     return "Finding player's location ";
  }

  public string MoveToPlayer()
  {
     return "Now I'm moving ";
  }
}

 internal keyword means that class is accessible from within the current assembly.

Second subclass will be very similar

internal class Speak
{
 public string SpeakToplayer()
 {
    return "Hi! How are You";
 }
}

 

Now lets implement the Facade Pattern into EnemyFacade Class.

class EnemyFacade
{
  Move a = new Move();
  Speak b = new Speak();

  public void Interact()
  {
    Console.WriteLine(a.FindPlayer());
    Console.WriteLine(a.MoveToPlayer());
    Console.WriteLine(b.SpeakToplayer());
  }
}

You need to create instances of each subclass in order to call the methods. My methods returns string variable so i can print result straight to the console.

Last part of code will be our client class that  calls the Facade method.

class Program
{
  static void Main(string[] args)
  {
    EnemyFacade facade = new EnemyFacade();

    facade.Interact();
  }
}

 

I simplified this as much as i could. Idea behind the pattern is very simple. Client calls only one method, and he is not interested in all the methods running in the background. This pattern is extremely useful in larger programs. I hope you will find this useful, in next article you will learn another super useful structural design pattern called Adapter. 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!