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# 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!

 

 

 

C# Factory Pattern

C# Factory Pattern tutorial

This is one of the creational patterns. Factory is used to create an object from instance of another class.  In Factory pattern, we create object without exposing the creation logic. This helps to deal with large and more complex programs. In this pattern, an interface is used for creating an object, but let subclass decide which class to instantiate. Creation process is done in run time.

1245px-factory_1b-svg

I’ll use example from typical video game where Enemy object is created, and its type is based on random number. Object is created in run time.

 

 

 

 

UML diagram:

l3

 

First let’s create Interface that will be shared between all enemies that can be crated with Factory. This will be used by client.

public interface IFactory
{
  void Demage(int dmg);
}

 

Now we need to create Classes that will inherit this interface. In my example this will be enemyType1 and 2.

public class EnemyType1 : IFactory
{
  int _health=100;
  public void Demage(int dmg)
  {
     _health -= dmg;
     Console.WriteLine("EnemyType1 health:" + _health.ToString());
  }
}

public class EnemyType2 : IFactory
{
  int _health = 200;
  public void Demage(int dmg)
  {
     _health -= dmg;
     Console.WriteLine("EnemyType2 health:" + _health.ToString());
  }
}

Both classes also contains health count, just to make it more interesting.

Next we need to create the Interface for factory itself.

public abstract class EnemyFactory
{
  public abstract IFactory InstantiateEnemy(int type);
}

As a return type we use interface IFactory, this way we can return any object that inherits from it.

In The factory Class we override the method with switch statement that will return the objects based on the input number.

public class InstantiateEnemyFactory : EnemyFactory
{
  public override IFactory InstantiateEnemy(int type)
  {
     switch (type)
     {
        case 1:
            return new EnemyType1();
        case 2:
           return new EnemyType2();
         default:
           throw new ApplicationException(string.Format("Wrong number"));
     }
  }
}

 

Last step is to create client that will use the factory class.

class Program
{
  static void Main(string[] args)
  {
  //random number
  int type = new Random().Next(1, 1000)% 2 + 1;
  //Instance of the class
  EnemyFactory factory = new InstantiateEnemyFactory();

  IFactory newEnemy= factory.InstantiateEnemy(type);
  newEnemy.Demage(20);

  type = new Random().Next(1, 2000)%2 + 1;

  IFactory newEnemy2 = factory.InstantiateEnemy(type);
  newEnemy2.Demage(20);

  Console.ReadKey();

  }
}

Numbers don’t have to be random. I’m using random numbers to demonstrate the example. I real world we would rather create a list of enemies rather than choosing name for each of them.

This patters is very simple and effective. This makes it commonly used across all languages. To conclude, Factory defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. I hope you found it useful and you will implement this pattern to your next project. 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!