C# Decorator Design Pattern

C# Decorator Design Pattern tutorial

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

C# Prototype Design Pattern tutorial

Link to source code

This is the last creational pattern in this series. And it’s used to create clones of objects without using references. C# is giving us helpful method MemberwiseClone() that is doing all cloning in the background. Later in the article I’ll cover the difference between Shadow and Deep Cloning.

The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.

In my example I’m creating copy of the Enemy object that will keep the same ID as the base object.

UML diagram

 

l10

Prototype

First thing to do is the interface that will be implemented by concrete class. This is an interface which is used for the types of object that can be cloned itself.


public abstract class AbstractEnemy
{
  int _id;

  public int Id
  {
    get { return _id; }
    set { _id = value; }
  }
  public abstract AbstractEnemy Clone();
}

This time implementation will be very simple thank to the MemberwiseClone() method.


class Enemy : AbstractEnemy
{
  public override AbstractEnemy Clone()
  {
      Console.WriteLine("cloning enemy...");
      return this.MemberwiseClone() as AbstractEnemy;
  }
}

One last thing to create is the Client Class that will create instance of an enemy and perform the cloning procedure.

Client

static void Main(string[] args)
{
   Enemy enemy = new Enemy();
   enemy.Id = 1;

   Console.WriteLine("Enemy Copy ID: " + enemy.Id.ToString());

   Enemy clonedEnemy = enemy.Clone() as Enemy;

   Console.WriteLine("Enemy Copy ID: " + clonedEnemy.Id.ToString());
 }
 }

 

Difference between Shadow and Deep Cloning

The problem with the memberwise copy is that it creates a shallow copy of the object i.e. if the object contains any reference types then only the address of that reference type will be copied from source to target and both the versions will keep pointing to the same object. Changing properties of inner-class of one object will change them for other class as well.

  • A shallow copy copies all reference types or value types, but it does not copy the objects that the references refer to. The references in the new object point to the same objects that the references in the original object points to.

  •  Deep copy of an object copies the elements and everything directly or indirectly referenced by the elements.

Solution to this problem is to create  new Copy() method that will involve copying the inner class properties to new object. or to include copy() method to all object sub classes, just as it was implemented in previous example.

 


 public override AbstractEnemy Clone()
 {
    Enemy cloned = this.MemberwiseClone() as Enemy;
    cloned.Equipment = new Equipment();
    cloned.Equipment.Armor = this.Equipment.Armor;

     return cloned as AbstractEnemy;
 }

To conclude, this pattern specifies the kind of objects to create using a prototypical instance, and create new objects by copying this prototype. I hope you learned something new. In next series of articles I’ll start moving into low level languages. Stay Awesome!

C# Abstract Factory Pattern

C# Abstract Factory Pattern tutorial

Link To source Code

In previous post i introduced you to the concept of Factory Method. Abstract factory is very similar, but this time we will encapsulate all classes, by cremating interfaces for  Product and Factory. This pattern is also called as Factory of factories, because this patterns acts a superFactory which creates other factories. Abstract factory pattern in useful when the client needs to create objects which are somehow related, without specifying the concrete class.  With this pattern objects can interact with each other through common interfaces.

As usual I am using example from game development. In my example I’ll create Abstract Factory that will spawn enemies and give them specific weapon and armor.

UML diagram

l9

 

Factory

First thing to crate is the interface for Factory, that will be used to specify the equipment of each enemy.


 interface IEnemyFactory
    {
       IWeapon GetWeapon();
       IArmor GetArmor();
    }

Concrete classes will be named as the type of enemy that will be created. In my Example i have two enemies Mage and Warrior.


class Mage : IEnemyFactory
{
    public IWeapon GetWeapon()
    {
        return new Wand();
    }

    public IArmor GetArmor()
    {
        return new Cloak();
    }
}

class Warrior : IEnemyFactory
{
    public IWeapon GetWeapon()
    {
        return new Sword();
    }

    public IArmor GetArmor()
    {
        return new BodyArmor();
    }
}

Product

In next step we will create interface for items that will be given to the enemies. Both types share the same types of equipment, weapon and armor.


interface IWeapon
 {
     string Item();
 }
interface IArmor
 {
     string Item();
 }

In Concrete classes methods will return string values that will be printed to the console.


class Sword : IWeapon
 {
     public string Item()
     {
         return "Iron Sword";
     }
 }

class Wand : IWeapon
 {
     public string Item()
     {
          return "Magic Wand";
     }
 }
 class BodyArmor : IArmor
 {
      public string Item()
      {
          return "Iron Body Armor";
      }
 }

class Cloak : IArmor
 {
     public string Item()
     {
          return "Magic Cloak";
     }
 }

Client

Client is the last part is to create. Here we will create instance of the factory and spawn our enemies.


class Client
{

IEnemyFactory factory=null;

//SpawnEnemy method will decide what type of enemy will be created

//Based on string input

public void SpawnEnemy(string enemy)
 {
   if (enemy == "Warrior")
   {
     factory = new Warrior();
     Console.WriteLine("New Warior equipment:");
     Console.WriteLine(factory.GetWeapon().Item());
     Console.WriteLine(factory.GetArmor().Item());
     Console.WriteLine("_____________________");
   }
   else if (enemy == "Mage")
   {
     factory = new Mage();
     Console.WriteLine("New Mage equipment: ");
     Console.WriteLine(factory.GetWeapon().Item());
     Console.WriteLine(factory.GetArmor().Item());
     Console.WriteLine("_____________________");
   }
   else
   {
      Console.WriteLine("Wrong type");
   }
 }

 //Main method
 static void Main(string[] args)
 {
     Client client = new Client();
     client.SpawnEnemy("Mage");
     client.SpawnEnemy("Warrior");
     Console.Read();
 }
}

To conclude, Abstract Factory  provides an interface for creating families of related or dependent objects without specifying their concrete classes. This pattern is very useful but in large projects it may increase the complexity of the code. I hope you learned something new today. In next article You will learn how to implement another pattern. Stay Awesome!

 

C# Command Design Pattern

C# Command Design Pattern Tutorial

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# Composite Pattern

C# Composite Pattern tutorial

Link to source code for this post

Composite pattern is used to create a tree structure, where every item of the structure implements the same interface. Therefore methods declared in interface can performed on every item in the structure. This pattern classifies each element in the tree as a composite or a leaf. A composite means that there can be other elements below it, whereas a leaf cannot have any elements below it.

To demonstrate the implementation of this pattern I’ll use an example of inventory where player can have Items( leafs ) and Backpack ( composite ). Player will be able to loop through all items in inventory and return the name of the items.

 

UML diagram

l5

 

First thing to create is the Component interface that will be inherited by all items in the structure.

public interface IInventory
{
  string Name { get; set; }
  void PrintName();
}

It acts as the base class for all the objects within the hierarchy. I’m creating name property for all items. you can find more about properties on my recent post about it.

Next thing is the implementation of the interface in Backpack Class that will be used to store Items or other Backpacks. To do this You need method for adding and removing items. Objects will be stored in generic List.


public class Backpack : IInventory, IEnumerable<IInventory>
{
  private List<IInventory> _subordinates = new List<IInventory>();

  public string Name { get; set; }

  public void AddSubordinate(IInventory subordinate)
  {
    _subordinates.Add(subordinate);
  }

  public void RemoveSubordinate(IInventory subordinate)
  {
    _subordinates.Remove(subordinate);
  }

  public IInventory GetSubordinate(int index)
  {
    return _subordinates[index];
  }

  public void PrintName()
  {
    Console.WriteLine(Name);
  }
  public IEnumerator<IInventory> GetEnumerator()
  {
    foreach (IInventory subordinate in _subordinates)
    {
      yield return subordinate;
    }
  }

  IEnumerator IEnumerable.GetEnumerator()
  {
    return GetEnumerator();
  }
}

Next thing is  to create an object Class, this class will be used to represent single item in inventory.

 public class Item : IInventory
{
  public string Name { get; set; }

  public void PrintName()
  {
    Console.WriteLine(Name);
  }
}

Last thing to do is the Client site that will create the structure based on the created Interface and Classes.

 class Program
{
  static void Main(string[] args)
  {
    Backpack inventory = new Backpack { Name = "Inventory" };
    Backpack backpack = new Backpack { Name = "Backpack" };

    inventory.AddSubordinate(backpack);
    inventory.AddSubordinate(new Item { Name = "Sword"});
    inventory.AddSubordinate(new Item { Name = "Armor" });

    backpack.AddSubordinate(new Item { Name = "Shield" });

    Console.WriteLine("List of items in inventory");

      foreach (IInventory element in inventory)
      {
         element.PrintName();
      }
    Console.ReadKey();
   }
 }

In this example Backpack class is used to create rot object for the tree. Where new backpack and few new items are added. Thanks to implementation of IEnumerable interface we can loop through items in the backpack class.

To conclude, Composite pattern compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. I hope you find this tutorial useful. If you have any questions feel free to ask in comments. In next part I’ll cover yet another design pattern. Stay Awesome!

C# Proxy Design Pattern

C# Proxy Design Pattern

Link To source Code for this article

This pattern is used to restrict access to Real Subject Class by creating Proxy gate, that implements the same interface as Real Subject and extends the interface methods to perform additional operations before executing method in Real Subject. Proxy Design Pattern acts as main point of contact for the resources that should not be available directly to the client code.

To demonstrate the implementation of this pattern I’ll use an example of in game equipment where access to the items is restricted by Proxy.

 

UML diagram:

l4

 

 

 

 

 

 

 

 

 

 

Let’s begin by creating Interface that will be implemented by both Classes.

public interface IEquipment
{
  string GetData();
}

Nothing fancy, just to demonstrate the idea behind the pattern. Subject Interface provides and interface that both actual class and proxy class will implement. this way the proxy can easily be used as substitute for the real subject.

Next step is to create Equipment Class that is our Real Subject

 public class Equipment : IEquipment
{
  string itemName;
  public int intemId;
  //Constructor
  public Equipment()
  {
    itemName = "Iron Sword";
    intemId = 4;
  }

  public string GetData()
  {
    return (itemName + " ID: "+ intemId.ToString());
  }
}

This class also contains one item with name and ID, which is represented just by fields, in more real example it would be list of Items. We assign new values when instance of this class is created.

Now we need to create Proxy that will have a reference to the Real Subject  and will modify the GetData() method to restrict the access.

public class EquipmentProxy : IEquipment
{
  Equipment client = new Equipment();

  public string GetData()
  {
     if (client.intemId == 4)
         return client.GetData();

     else
         return "Item is not in inventory";
   }
 }

Id is hard typed and set to 4 just for the example. The application will use this class and this class will internally take care of talking to the RealSubject and get the data to the local application.

Last part of the application is Client site, where Instance of the proxy is created and GetData() method is called.

class Program
{
  static void Main(string[] args)
  {
     EquipmentProxy proxy = new EquipmentProxy();
     Console.WriteLine("Data from Proxy: "+ proxy.GetData());

     Console.ReadKey();
  }
}

 

To conclude, The proxy design pattern is used to provide a surrogate object, which references to other object. Proxy pattern involves a class, called proxy class, which represents functionality of another class. I hope you learned something new, in next article I’ll cover another design pattern. Stay Awesome!