Wednesday, April 10, 2013

Singleton Design Pattern C#

Design patterns are recurring solutions to software design problems we find again and again in real-world object oriented application development.

Design patterns are there to address a variety of design problems, from small issues to large, architecture-level problems.

Here, I am starting a thread which explains different categories of design patterns and their usage.

Design patterns are not language specific. Here I have tried to use C# to demonstrate design patterns examples.

Design patterns are categorized in three groups: Creational, Structural, and Behavioral.

I will be using following format to explain design pattern to make it consistent across all patterns.

Name and Category: Describes the name of the pattern and category of pattern (Creational, Structural, or) Behavioral).

Intent: It describes what kind of design problem this pattern addresses.

Motivation: A scenario that illustrates a design problem and how the class and object structures in the pattern solve the problem.

Consequences: It will describe the trade-offs of design pattern.

_________________________________________________________________________________________________________________

In this article we will have a look at Singleton design pattern.

Name and Category: Singleton (Creational Pattern)

Intent: Ensure a class only has one instance, and provide a global point of access to it.

Motivation: Sometimes we want just a single instance of a class to exist in the system
For example; we want just one window manager. Or just one factory for a
family of products.


Let us look into implementation.

How can I make only one instance of my class?

First, we will create a private constructor of our class.

When constructor is a private then object of that class can not be created at all.

Here, we are restricting user from creating an instance of a class. But as per our requirement we need to have one and only one constructor.

In order to achieve that, we will create a one static method which in turn returns an object of class.

Here, is how it goes:

// Class : Singleton.cs

using System;
using System.Collections.Generic;
using System.Text;
namespace DesignPattern
{
class Singleton
{
private static Singleton singleton = null;

/**
* Returns a reference to the single instance.
* Creates the instance if it does not yet exist.
* (This is called lazy instantiation.) 
*/
public static Singleton Instance()
{
if (null == singleton)
singleton = new Singleton();
return singleton;
}
/** The Singleton Constructor.
* Note that it is private!
* No client can instantiate a Singleton object!
*/
private Singleton()
{
}
}
}



Here, we have a static method Instance() which takes care of single instance.

In this method first we check whether the static private variable singleton is created or not.

If it is null it will create a constructor.

If it is not null it will return the existing one.

So we are sure that only one instance of our class will be created.

Now let us think in different way. If two threads are trying to access the Instance () method at the same time what will happen?

In that case we will be having two instance of our class> It means our class is not a singleton. right??

So, how can we achieve singleton object?



// Class : Singleton.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace DesignPattern
{
class Singleton
{
private static Singleton singleton = null;
// Lock synchronization object
private static object syncLock = new object();



/**
* Returns a reference to the single instance.
* Creates the instance if it does not yet exist.
* (This is called lazy instantiation.)
*/
public static Singleton Instance()
{
/* Support multithreaded applications through
* 'Double checked locking' pattern which (once
* the instance exists) avoids locking each
* time the method is invoked
*/
if (null == singleton)
{
lock (syncLock)
{
if (singleton == null)
{
singleton = new Singleton();}
}
}
return singleton;
}
/* The Singleton Constructor.
* Note that it is private!
* No client can instantiate a Singleton object!
*/
private Singleton()
{ 
}
}
}


This will make sure that only single instance of class will be created.

Consequences:

Benefits: 1) Controlled access to sole instance.

Monday, April 8, 2013

C# 4.0 - Named and Optional Arguments

C# 4.0 has new feature called Named and Optional Arguments. Named parameters are useful  to provide a way to pass the arguments by name. This is really helpful when the number of parameters are too many.

  Optional parameters are also useful in a way that it can help lot to avoid unnecessary parameters in method call.
 
 There was a way to pass optional parameters since the early days of C# 1.0. We had param keyword using that we can pass optional parameters. But the limitations of param is the user can not provide multi type  optional parameters .  The another drawback of param is the optional parameters have to be the last parameters only.  
 
 C# 4.0 addresses all the problems that we have with earlier versions of C#.   It provides easy to use syntax.  
 
public int AddNumbers(int n1, int n2=10, int n3=30, int n4=40);
 
To mark the parameters as optional it is compulsory to provide default values for optional arguments.   In above example n2,n3 and n4 are optional parameters.
 
The above method can be called in following way.
 
AddNumber(10,20,30,40);  // Providing all the parameters.
AddNumber(100,200,300);  // Not providing the value for n4.
AddNumber(10,20);        // Not providing the value for n3 and n4.
AddNumber(100);  // Not providing the value for n2, n3 and n4.
 
 
When value for optional parameters is not provided it will take the default value for that parameter which is defined in method definition.  Here in case of last method AddNumber(100) the value for n2, n3 and n4 will be taken as 20,30 and 40 respectively. 
 
 
class TestArguments
    {
        /// <summary>
        /// MEthods having Optional parameteres.
        /// Note : Optioanl arguments are declared by simply providing default valus for paramteres.
        /// </summary>
        /// <param name="n1">First number which is not optional.</param>
        /// <param name="n2">2nd number having default value hence optional</param>
        /// <param name="n3">3nd number having default value hence optional</param>
        /// <param name="n4">4nd number having default value hence optional</param>
        /// <returns></returns>
        public int AddNumbers(int n1, int n2=10, int n3=30, int n4=40)
        {
            return n1 + n2 + n3 + n4;
        }
    }
 
 
 
 
 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace CSharp4
{
    class Program
    {
        static void Main(string[] args)
        {
            
            TestArguments objTestArg = new TestArguments();
            int result = 0;
 
            //calling the method with 4th parameter as optional
            result = objTestArg.AddNumbers(10, 100,200);
            Console.WriteLine(result);
 
            //calling the method with 3rd and 4th parameters as optional
            result = objTestArg.AddNumbers(10, 20);
            Console.WriteLine(result);
 
            //calling the method with 2nd, 3rd and 4rd parameters as optional
            result = objTestArg.AddNumbers(10);
            Console.WriteLine(result);
 
            Console.ReadLine();
        }
    }
}
 
 
You can see in above example the various way to call AddNumber() methods with optional arguments.

Named arguments

 
C# 4.0 has another cool feature which lets the user to call method by providing named parameters for methods.
 
C# 4.0 does not allow to skip arguments between  commas such as  in M(1,,3) but we can pass any argument by name instead. 
 
For  examples : 
    AddNumbers(10, n4: 3); // passing value of n4  by name
Or
    AddNumbers (n1:100, n4:200 n2: 3); //passing n1,n4 & n3 in different order
 
Or
 
AddNumbers(n1:100 , n3:200); // passing n2 and n3.
 
 
Above all method call parameters are valid. When parameters are not in the same order as it  defined in method signature, arguments are always evaluated in order they are passed.
 
 
Optional and named arguments can be also be used with indexers and constructors.
Software Development Blogs - BlogCatalog Blog Directory RSS Search Technology Blogs - Blog Rankings Blog Directory