C# Prototype Design Pattern

C# Prototype Design Pattern tutorial

Advertisements

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

 

 

 

 

 

 

Singleton Pattern C#

Singleton Pattern C# tutorial

Singleton Pattern is one the most popular patterns in programming. Singleton is a class which only allows a single instance of itself to be created. It can be very useful, for example when Class contains List of object we don’t want to create new list each time we call the class, and we also want to keep the list private to restrict access and avoid possible corruption. Singleton usually gives simple access to that instance. There are several ways of implementing the pattern, in multi-threading application we must consider case where constructor is called from two thread at the same time, to fix this problem we need to implement thread safety version. Let start with simplest, not thread safe, implementation.

public class Singleton
{
  private static Singleton instance;

  private Singleton() { }

  public static Singleton Instance
  {
    get
    {
       if (instance == null)
       {
          instance = new Singleton();
       }
       return instance;
    }
  }
 }

This Singleton class contains private static Singleton Class instance. Those keywords are very important, Private makes the instance accessible only from current class( Instance getter)  what prevents other classes from accessing it in not safe way. Static makes it shared across all instances. You can find more about statics, here.

Constructor of this class( Singleton() ) is private, and its called from Instance getter, if its not created yet.

Instance property is read only and it returns the instance of the class, always the same instance for all calls. If you don’t know how get{} works, check my post about it  here.

Here is thread safety version of this Pattern, It prevents from creating two instances when getter is called from multiple threads.

First we need to add object that will be responsible for handling multiple thread access.


private static readonly object padlock = new object();

New we need to add one condition to Instance parameter that will lock the firs thread that is accessing it.

public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }

 

All these implementations share four common characteristics, however:

  • A single constructor, which is private and parameterless.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.

 

In next post You will see real word examples of using this patter. One day I’ll demonstrate how to use it In Unity to create MusicManager, that is playing music between game scenes. Singleton have many uses and It’s one of the simplest patterns to learn. In next articles I’ll try to describe all most popular design patterns. Stay Awesome!