Wednesday, 11 May 2016

Singleton Design Pattern - C#

Singleton pattern falls under Creational Pattern of Gang of Four (GOF) Design Patterns in .Net. It is pattern is one of the simplest design patterns. This pattern ensures that a class has only one instance. In this article, I would like share what is Singleton pattern and how is it work?

What is Singleton Pattern?

Singleton pattern is one of the simplest design patterns. This pattern ensures that a class has only one instance and provides a global point of access to it.

Singleton Pattern - UML Diagram & Implementation

The UML class diagram for the implementation of the Singleton design pattern is given below:
The classes, and objects in the above UML class diagram are as follows:
  1. Singleton

    This is a class which is responsible for creating and maintaining its own unique instance.

C# - Implementation Code

  1. //eager initialization of singleton
  2. public class Singleton
  3. {
  4. private static Singleton instance = new Singleton();
  5. private Singleton() { }
  6.  
  7. public static Singleton GetInstance
  8. {
  9. get
  10. {
  11. return instance;
  12. }
  13. }
  14. }
  15.  
  16. ////lazy initialization of singleton
  17. public class Singleton
  18. {
  19. private static Singleton instance = null;
  20. private Singleton() { }
  21.  
  22. public static Singleton GetInstance
  23. {
  24. get
  25. {
  26. if (instance == null)
  27. instance = new Singleton();
  28.  
  29. return instance;
  30. }
  31. }
  32. }
  33.  
  34. ////Thread-safe (Double-checked Locking) initialization of singleton
  35. public class Singleton
  36. {
  37. private static Singleton instance = null;
  38. private Singleton() { }
  39. private static object lockThis = new object();
  40.  
  41. public static Singleton GetInstance
  42. {
  43. get
  44. {
  45. lock (lockThis)
  46. {
  47. if (instance == null)
  48. instance = new Singleton();
  49.  
  50. return instance;
  51. }
  52. }
  53. }
  54. }

Singleton Pattern - Example

Who is what?

The classes and objects in the above class diagram can be identified as follows:
  1. Singleton - Singleton class

C# - Sample Code

  1. /// <summary>
  2. /// The 'Singleton' class
  3. /// </summary>
  4. public class Singleton
  5. {
  6. // .NET guarantees thread safety for static initialization
  7. private static Singleton instance = null;
  8. private string Name{get;set;}
  9. private string IP{get;set;}
  10. private Singleton()
  11. {
  12. //To DO: Remove below line
  13. Console.WriteLine("Singleton Intance");
  14.  
  15. Name = "Server1";
  16. IP = "192.168.1.23";
  17. }
  18. // Lock synchronization object
  19. private static object syncLock = new object();
  20.  
  21. public static Singleton Instance
  22. {
  23. get
  24. {
  25. // Support multithreaded applications through
  26. // 'Double checked locking' pattern which (once
  27. // the instance exists) avoids locking each
  28. // time the method is invoked
  29. lock (syncLock)
  30. {
  31. if (Singleton.instance == null)
  32. Singleton.instance = new Singleton();
  33.  
  34. return Singleton.instance;
  35. }
  36. }
  37. }
  38.  
  39. public void Show()
  40. {
  41. Console.WriteLine("Server Information is : Name={0} & IP={1}", IP, Name);
  42. }
  43.  
  44. }
  45.  
  46. /// <summary>
  47. /// Singleton Pattern Demo
  48. /// </summary>
  49. ///
  50. class Program
  51. {
  52. static void Main(string[] args)
  53. {
  54. Singleton.Instance.Show();
  55. Singleton.Instance.Show();
  56.  
  57. Console.ReadKey();
  58. }
  59. }

Singleton Pattern Demo - Output

When to use it?

  1. Exactly one instance of a class is required.
  2. Controlled access to a single object is necessary

Design Pattern Implementation using C#


Introduction


Design patterns may be said as a set of probable solutions for a particular problem which is tested to work best in certain situations. In other words, Design patterns, say you have found a problem. Certainly, with the evolution of software industry, most of the others might have faced the same problem once. Design pattern shows you the best possible way to solve the recurring problem.

Uses of Design Patterns

While creating an application, we think a lot on how the software will behave in the long run. It is very hard to predict how the architecture will work for the application when the actual application is implemented completely. There might issues which you cant predict and may come while implementing the software. Design patterns helps you to find tested proven design paradigm to build a solid foundation for your project. So, if you follow design pattern you can easily prevent major issues to come while building your actual project. Moreover design pattern also helps the other architects to understand your code easily.

History of Design Patterns

When the word design pattern comes into mind, the first thing that one may think is the classical book on Design Pattern "Gangs of Four" which was published by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.  In this book, it is first discussed capabilities and pitfalls of Object oriented programming, and later on it discusses about the classic Design Patterns on OOPS.

You can read more about history of design patterns from here.

Types of Design Pattern


Design patterns can be divided into 3 categories.

  1. Creational Patterns : These patterns deals mainly with creation of objects and classes.
  2. Structural Patterns : These patterns deals with Class and Object Composition.
  3. Behavioural Patterns : These mainly deals with Class - Object communication. That means they are concerned with the communication between class and objects.
In this article, I am going to discuss few examples of these patterns. They are
  • Singleton Design Pattern
  • Factory Design Pattern
  • Factory Method Design Pattern
  • Abstract Factory Design Pattern,
  • Builder Design Pattern,
  • Prototype Design Pattern
  • Adapter Design Pattern
  • Bridge Design Pattern
  • Decorator Design Pattern
  • Composite Design Pattern
  • Flyweight Design Pattern
  • Memento Design Pattern
  • Mediator Design Pattern
  • Observer Design Pattern
  • Iterator Pattern

CREATIONAL PATTERNS

Singleton Pattern

Singleton pattern creates a class which can have a single object throughout the application, so that whenever any other object tries to access the object of the class, it will access the same object always.



/// <summary>
/// Implementation of Singleton Pattern
/// </summary>
public sealed class SingleTon { private static SingleTon _instance = null; private SingleTon() // Made default constructor as private

{

}

/// <summary>

/// Single Instance

/// </summary>

public static SingleTon Instance
{
get

{


lock (_instance)
{
_instance = _instance ?? new SingleTon();
return _instance;
}
}
}

# region Rest of Implementation Logic
//Add As many method u want here as instance member.No need to make them static

# endregion
}
In the above code you can see I have intentionally made the constructor as private. This will make sure that the class cant be instantiated from outside. On the other hand, you also need to make a property which will return the static instance of the object present within the class itself. Hence the object will be shared between all the external entities.

Factory Pattern

Factory pattern deals with the instantiation of object without exposing the instantiation logic. In other words, a Factory is actually a creator of object which has common interface.


//Empty vocabulary of Actual object
public interface IPeople
{

string GetName();
}
public class Villagers : IPeople
{

#region IPeople Members
public string GetName()
{
return "Village Guy";
}

#endregion
}
public class CityPeople : IPeople
{

#region IPeople Members
public string GetName()
{
return "City Guy";
}

#endregion
}
public enum PeopleType
{
RURAL,
URBAN
}
/// <summary>
/// Implementation of Factory - Used to create objects
/// </summary>
public class Factory
{

public IPeople GetPeople(PeopleType type)
{
IPeople people = null;
switch (type)
{
case PeopleType.RURAL:
people = new Villagers();
break;
case PeopleType.URBAN:
people = new CityPeople();
break;
default:
break;
}
return people;
}
}
In the above code you can see I have created one interface called IPeople and implemented two classes from it as Villagers andCityPeople. Based on the type passed into the factory object, I am sending back the original concrete object as the Interface IPeople.
Factory Method

A Factory method is just an addition to Factory class. It creates the object of the class through interfaces but on the other hand, it also lets the subclass to decide which class to be instantiated.


public interface IProduct
{

string GetName();
string SetPrice(double price);
}
public class IPhone : IProduct
{

private double _price;

#region IProduct Members
public string GetName()
{
return "Apple TouchPad";
}
public string SetPrice(double price)
{
this._price = price;
return "success";
}

#endregion
}
/* Almost same as Factory, just an additional exposure to do something with the created method */
public abstract class ProductAbstractFactory
{

public IProduct DoSomething()
{
IProduct product = this.GetObject();
//Do something with the object after you get the object.

product.SetPrice(20.30);

return product;
} public abstract IProduct GetObject();
}
public class ProductConcreteFactory : ProductAbstractFactory
{

public override IProduct GetObject() // Implementation of Factory Method.

{


return this.DoSomething();
}
}
You can see I have used GetObject in concreteFactory. As a result, you can easily call DoSomething() from it to get the IProduct.

You might also write your custom logic after getting the object in the concrete Factory Method. The GetObject is made abstract in the Factory interface.
Abstract Factory

Abstract factory is the extension of basic Factory pattern. It provides Factory interfaces for creating a family of related classes. In other words, here I am declaring interfaces for Factories, which will in turn work in similar fashion as with Factories.


public interface IFactory1
{
IPeople GetPeople();
}
public class Factory1 : IFactory1
{

public IPeople GetPeople()
{
return new Villagers();
}
}
public interface IFactory2
{
IProduct GetProduct();
}
public class Factory2 : IFactory2
{

public IProduct GetProduct()
{
return new IPhone();
}
}
public abstract class AbstractFactory12
{

public abstract IFactory1 GetFactory1();
public abstract IFactory2 GetFactory2();
}
public class ConcreteFactory : AbstractFactory12
{

public override IFactory1 GetFactory1()
{
return new Factory1();
}
public override IFactory2 GetFactory2()
{
return new Factory2();
}
}
The factory method is also implemented using common interface each of which returns objects.


Builder Pattern

This pattern creates object based on the Interface, but also lets the subclass decide which class to instantiate. It also has finer control over the construction process. There is a concept of Director in Builder Pattern implementation. The director actually creates the object and also runs a few tasks after that. 



public interface IBuilder
{

string RunBulderTask1();
string RunBuilderTask2();
}
public class Builder1 : IBuilder
{

#region IBuilder Members
public string RunBulderTask1()
{
throw new ApplicationException("Task1");
}
public string RunBuilderTask2()
{
throw new ApplicationException("Task2");
}

#endregion
}
public class Builder2 : IBuilder
{

#region IBuilder Members
public string RunBulderTask1()
{
return "Task3";
}
public string RunBuilderTask2()
{
return "Task4";
}

#endregion
}
public class Director
{

public IBuilder CreateBuilder(int type)
{
IBuilder builder = null;
if (type == 1)
builder = new Builder1();
else

builder = new Builder2();
builder.RunBulderTask1();
builder.RunBuilderTask2();
return builder;
}
}
In case of Builder pattern you can see the Director is actually using CreateBuilder to create the instance of the builder. So when the Bulder is actually created, we can also invoke a few common task in it.


Prototype Pattern

This pattern creates the kind of object using its prototype. In other words, while creating the object of Prototype object, the class actually creates a clone of it and returns it as prototype.


public abstract class Prototype
{

// normal implementation

public abstract Prototype Clone();
}
public class ConcretePrototype1 : Prototype
{

public override Prototype Clone()
{
return (Prototype)this.MemberwiseClone();
}
}
class ConcretePrototype2 : Prototype
{

public override Prototype Clone()
{
return (Prototype)this.MemberwiseClone(); // Clones the concrete class.

}
}
You can see here, I have used MemberwiseClone method to clone the prototype when required.  You must remember,MemberwiseClone is actually a swallow copy. To make it copy deep, you need to call MemberwiseClone recursively for every object until its value types.

STRUCTURAL PATTERN


 
Adapter Pattern

Adapter pattern converts one instance of a class into another interface which client expects. In other words, Adapter pattern actually makes two classes compatible.


public interface IAdapter
{

/// <summary>

/// Interface method Add which decouples the actual concrete objects

/// </summary>

void Add();
}
public class MyClass1 : IAdapter
{

public void Add()
{
}
}
public class MyClass2
{

public void Push()
{
}
}
/// <summary>
/// Implements MyClass2 again to ensure they are in same format.
/// </summary>
public class Adapter : IAdapter
{

private MyClass2 _class2 = new MyClass2();
public void Add()
{
this._class2.Push();
}
}

Here in the structure, the adapter is used to make MyClass2 incompatible with IAdapter.

Bridge Pattern

Bridge pattern compose objects in tree structure. It decouples abstraction from implementation. Here abstraction represents the client where from the objects will be called.


# region The Implementation
/// <summary>
/// Helps in providing truely decoupled architecture
/// </summary>
public interface IBridge
{

void Function1();
void Function2();
}
public class Bridge1 : IBridge
{

#region IBridge Members
public void Function1()
{
throw new NotImplementedException();
}
public void Function2()
{
throw new NotImplementedException();
}

#endregion
}
public class Bridge2 : IBridge
{

#region IBridge Members
public void Function1()
{
throw new NotImplementedException();
}
public void Function2()
{
throw new NotImplementedException();
}

#endregion
}
# endregion
# region Abstraction
public interface IAbstractBridge
{

void CallMethod1();
void CallMethod2();
}
public class AbstractBridge : IAbstractBridge
{

public IBridge bridge;
public AbstractBridge(IBridge bridge)
{
this.bridge = bridge;
}

#region IAbstractBridge Members
public void CallMethod1()
{
this.bridge.Function1();
}
public void CallMethod2()
{
this.bridge.Function2();
}

#endregion
}
# endregion

Thus you can see the Bridge classes are the Implementation, which uses the same interface oriented architecture to create objects. On the other hand the abstraction takes an object of the implementation phase and runs its method. Thus makes it completely decoupled with one another.

Decorator Pattern

Decorator pattern is used to create responsibilities dynamically. That means each class in case of Decorator pattern adds up special characteristics.In other words, Decorator pattern is the same as inheritance.



public class ParentClass
{

public void Method1()
{
}
}
public class DecoratorChild : ParentClass
{

public void Method2()
{
}
}
This is the same parent child relationship where the child class adds up new feature called Method2 while other characteristics is derived from the parent.
Composite Pattern

Composite pattern treats components as a composition of one or more elements so that components can be separated between one another. In other words, Composite patterns are those for whom individual elements can easily be separated.



/// <summary>
/// Treats elements as composition of one or more element, so that components can be separated
/// between one another
/// </summary>
public interface IComposite
{

void CompositeMethod();
}
public class LeafComposite : IComposite
{

#region IComposite Members
public void CompositeMethod()
{
//To Do something

}

#endregion
}
/// <summary>
/// Elements from IComposite can be separated from others
/// </summary>
public class NormalComposite : IComposite
{

#region IComposite Members
public void CompositeMethod()
{
//To Do Something

}

#endregion

public void DoSomethingMore()
{
//Do Something more .

}
}
Here in the code you can see that in NormalCompositeIComposite elements can easily be separated.
Flyweight Pattern

Flyweight allows you to share bulky data which are common to each object. In other words, if you think that same data is repeating for every object, you can use this pattern to point to the single object and hence can easily save space.

/// <summary>
/// Defines Flyweight object which repeats iteself.
/// </summary>
public class FlyWeight
{

public string Company { get; set; }
public string CompanyLocation { get; set; }
public string CompanyWebSite { get; set; }
//Bulky Data

public byte[] CompanyLogo { get; set; }
}
public static class FlyWeightPointer
{

public static FlyWeight Company = new FlyWeight

{


Company = "Abc",
CompanyLocation = "XYZ",
CompanyWebSite = "www.abc.com"

};
}
public class MyObject
{

public string Name { get; set; }
public FlyWeight Company
{
get

{


return FlyWeightPointer.Company;
}
}
}

Here the FlyweightPointer creates a static member Company, which is used for every object of MyObject.


Memento Pattern

Memento pattern allows you to capture the internal state of the object without violating encapsulation and later on you can undo/ revert the changes when required.


public class OriginalObject
{

public string String1 { get; set; }
public string String2 { get; set; }
public Memento MyMemento { get; set; }
public OriginalObject(string str1, string str2)
{
this.String1 = str1;
this.String2 = str2;
this.MyMemento = new Memento(str1, str2);
}
public void Revert()
{
this.String1 = this.MyMemento.String1;
this.String2 = this.MyMemento.String2;
}
}
public class Memento
{

public string String1 { get; set; }
public string String2 { get; set; }
public Memento(string str1, string str2)
{
this.String1 = str1;
this.String2 = str2;
}
}
Here you can see the Memento Object is actually used to Revert the changes made in the object.


BEHAVIOURAL PATTERN


 

Mediator Pattern

Mediator pattern ensures that the components are loosely coupled, such that they don't call each others explicitly, rather they always use a separate Mediator implementation to do those jobs.


public interface IComponent
{

void SetState(object state);
}
public class Component1 : IComponent
{

#region IComponent Members
public void SetState(object state)
{
//Do Nothing

throw new NotImplementedException();
}

#endregion
}
public class Component2 : IComponent
{

#region IComponent Members
public void SetState(object state)
{
//Do nothing

throw new NotImplementedException();
}

#endregion
}
public class Mediator // Mediages the common tasks
{

public IComponent Component1 { get; set; }
public IComponent Component2 { get; set; }
public void ChageState(object state)
{
this.Component1.SetState(state);
this.Component2.SetState(state);
}
}

Here you can see the Mediator Registers all the Components within it and then calls its method when required.


Observer Pattern


When there are relationships between one or more objects, an observer will notify all the dependent elements when something is modified in the parent. Microsoft already implemented this pattern as ObservableCollection. Here let me implement the most basic Observer Pattern.

public delegate void NotifyChangeEventHandler(string notifyinfo);
public interface IObservable
{

void Attach(NotifyChangeEventHandler ohandler);
void Detach(NotifyChangeEventHandler ohandler);
void Notify(string name);
}
public abstract class AbstractObserver : IObservable
{

public void Register(NotifyChangeEventHandler handler)
{
this.Attach(handler);
}
public void UnRegister(NotifyChangeEventHandler handler)
{
this.Detach(handler);
}
public virtual void ChangeState()
{
this.Notify("ChangeState");
}

#region IObservable Members
public void Attach(NotifyChangeEventHandler ohandler)
{
this.NotifyChanged += ohandler;
}
public void Detach(NotifyChangeEventHandler ohandler)
{
this.NotifyChanged -= ohandler;
}
public void Notify(string name)
{
if (this.NotifyChanged != null)
this.NotifyChanged(name);
}

#endregion

#region INotifyChanged Members
public event NotifyChangeEventHandler NotifyChanged;

#endregion
}
public class Observer : AbstractObserver
{

public override void ChangeState()
{
//Do something.

base.ChangeState();
}
}
You can definitely got the idea that after you Register for the Notification, you will get it when ChangeState is called.


Iterator Pattern


This pattern provides a way to access elements from an aggregate sequentially. Microsoft's IEnumerable is one of the example of this pattern. Let me introduce this pattern using this interface.


public class Element
{

public string Name { get; set; }
}
public class Iterator : IEnumerable<Element>
{
public Element[] array;
public Element this[int i]
{
get

{


return array[i];
}
}

#region IEnumerable<Element> Members
public IEnumerator<Element> GetEnumerator()
{
foreach (Element arr in this.array)
yield return arr;
}

#endregion


#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
foreach (Element arr in this.array)
yield return arr;
}

#endregion
}
In the above code you can see I have implemented IEnumerable which actually corresponds to the Iterator block. You can also implement it yourself, just by adding few methods like First()Last(), Next() etc. As they are already implemented as extension method with IEnumerable, I have just made it simpler using it.


download project code link-
http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhi2434_Articles_634098948511041015_DesignPatterns.zip