Design Patterns for all – Chapter II (Singleton Pattern)

Monday, June 22, 2009

Design Patterns for all – Chapter II (Singleton Pattern)

In the previous chapter we saw the basics of Design patterns and OOPs which will give the foundation for understanding Design patterns better. In this chapter we are going to see the Singleton Pattern in detail with c# coding.

Singleton Pattern:
It comes under the category of ‘Creational Pattern’.

Definition:

It allows a single instance of a class and provides global access to it.

Steps to implement a Singleton Pattern in C#:
1. Create a sealed class.
2. Declare a private variable for that class inside the class.
3. Make the constructor as private.
4. Create a public static property which only returns the instance
5. Inside that use lock() to handle the object instance for supporting multi-threading functionality.

Applicability:
1. Logger
It is primarily used in the areas where single access channel is needed. Logging is an area where it is primarily used.
2. Db Connection
For managing database connections also it is used as there should be only one connection at a time.
3. Configuration Manager
Then configuration managers, which read and write to configuration files, there also Singletons are used.

A Logger example in C#:
Steps to write it:
1. Select Visual studio > Project > C# & Windows Application.
2. Follow the steps given in the steps to write a Singleton class above
3. The complete code of the Singleton Pattern and its usage class are given below :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace SingletonDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
MySingleton sg = MySingleton.Instance;
sg.LogMyError("test");
}
}


public sealed class MySingleton
{
private static volatile MySingleton instSingleton;
private static object objSynformultithread = new Object();

private MySingleton()
{
}

public void LogMyError(String msg)
{
TextWriter twLog = new StreamWriter("c:\\log.txt");

// write a line of text to the file
twLog.WriteLine("Start" + DateTime.Now);
twLog.WriteLine(msg);
twLog.WriteLine("End");
// close the stream
twLog.Close();
}


public static MySingleton Instance
{
get
{
if (instSingleton == null)
{
lock (objSynformultithread)
{
if (instSingleton == null)
instSingleton = new MySingleton();
}
}

return instSingleton;
}
}
}
}

Explanations over the Program:

Purpose of Sealed:
It prevents derivation which could add instances.

Purpose of Private Static Volatile:
Private, it makes the variable private and so not accessible from outside.
Static, without creating instance (only the instance created inside) we can call with name of the class as MySingleton.variable.
Volatile, makes the instance variable assignment completed before it is accessed.

Purpose of Lock:
It avoids deadlocks, enables multithreaded functionality.

The above program has the function LogMyError which does the logging to the file system. You can change the file name and path wherever you want it to get stored. Moreover it was written for a demo purpose only, so its not that much fuller. You need to add the append functionality to it such that it works as according to your need.

If you do the minor modifications based on your need of logging then it will be a good Logger for any kind of application.
Similarly it can be used for DB Connection, Configuration Management, etc.

Design Patterns for all – Chapter I (Introduction to Design patterns and OOPs)

Design Patterns for all – Chapter I (Introduction to Design patterns and OOPs)
In this chapter we will see the basics of Design patterns and OOPs which will give the foundation for understanding Design patterns better. In the coming chapters we will see the Design patterns in detail with practical examples and code.

Definition:

Design Patterns are best proven techniques for a common design problem.
It is only a design technique and not code. Though code is available for almost all design patterns in all popular languages, design patterns mean the design technique alone.
Each design pattern explains a repeated problem, gives standard solution to the problem.

History:
GoF Gang of four, a four member team (Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides) are said to be people who brought up this idea. They wrote some patterns which are considered the base for all other patterns.

Types of Patterns:
Design Patterns are generally classified into three categories, they are:
1. Creational
2. Structural
3. Behavioral

1. Creational
They deal with object creation. They provide you the best way to create objects based on the current situation.
Example:
Singleton, Factory method, Abstract factory, Builder

2. Structural
They deal with relationship between entities. They provide you the best way to relate entities on various scenarios.
Example:
Adapter, Aggregate, Bridge

3. Behavioral
They deal with communication between objects. They provide you the best way to communicate between objects.
Example:
Chain of responsibility, Command, Interpreter

Further Classification:
Though the above three are the major classification, one more category also exists which may be considered as a sub part of the above. It is:

Concurrency
They deal with multi-threaded programs. They provide solutions for multi-thread design problems.
Example:
Balking, Double checked locking, guarded suspension

OOP Techniques and Design Patterns:
Before going into design patterns, we need to know some of the OOP (Object Oriented Programming) features, which will in turn lead to a better understanding of Design patterns.
Let us now see the OOPs features one by one,

Class:
It defines characteristics of a thing and its behavior. It is blueprint from based on which objects are created.
Example: Employee (which will have all the details about the employee like name, id, salary, etc and the methods which describes his behavior like calcSalary(),displaydetails(),etc.

Object:
Is an instance of a class. It will be exactly the same as a class but can be assigned values and used whereas a class can’t be used without creating objects.

Inheritance:
A feature in which the base class’s characteristics and behavior are derived to the child class also.
Types:
Single
Multiple

Single:
A class inherits from a single class.
Multiple:
A class inherits from more than 1 class.

Abstraction:
“Abstraction is simplifying complex reality by modeling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem.” Is what the Wikipedia says.

Encapsulation:
It is a feature which hides data and functions from others classes.

Polymorphism:
A feature using which more than one definition is given to a single name. It can either be function polymorphism or operator overloading.

Association:
Association defines a relationship between classes of objects which allows one object to cause another to perform an action on its behalf.

Composition:
Composition is a way to combine simple objects or data types into more complex ones.

Aggregation:
Aggregation is a form of composition where one looks at the system as a whole rather than as parts.

LinkWithin

Blog Widget by LinkWithin

Recommended Books