Sunday, May 10, 2009

Lazy Initialzation Pattern in C#





Intent:

Delaying the creation of the object until the first time it has been requested.

Lazy initialization is the tactics of delaying the process of creation of object or calculating the value of the object or some other expansive processes until the first time it is needed. Typically it is achieved by maintaining a flag value in the code. Based on the flag value if the object is ready it is served from the available resources. If not available the object is created on the spot and the request is served.

Benefits:


The main advantage of using the Lazy initialization is that it will not consume unnecessary expansive resources for creating the object until it is required for the first time. Also if the object is already created the request is being served from the object created instead of creating a new object.

Software Example & Explanation of Code:

Let us assume that we are building an online Library Management System. One of the pages (aspx page) requires you to create object of different books. Using the Lazy initialization pattern we will see how the construction of object is delayed till it is requested for the first time. Also when we make request for an object which is already existing how the object is being served from the existing object rather than creating a new one.

Typically Lazy initialization is using with either Factory Method pattern or Single ton design pattern. Here in our example the class “LibraryBooks” does the late initialization of LibraryBooks objects and also if any of the book type already exists it serves it from the existing objects rather than creating new object. The client which is our asp.net page (“Default.aspx” in our case) makes request to the “LibraryBooks” class for creating new objects. Below is the code for the pattern



LibraryBooks.cs

using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.Collections.Generic;

namespace LazyInitialzation
{
public class LibraryBooks
{
private static Dictionary objLibraryBooks = new Dictionary();
private string strBookType;

//using a Private constuctor to for Factory or Singleton Methos
private LibraryBooks(string _type)
{
this.strBookType = _type;
}
//Here we are passing the book type and the return type is LibraryBook type
public static LibraryBooks GetBooks(string _BookType)
{
LibraryBooks objBooks;

if (!objLibraryBooks.TryGetValue(_BookType, out objBooks))
{
objBooks = new LibraryBooks(_BookType); //Lazy Initialization
objLibraryBooks.Add(_BookType, objBooks);
}
return objBooks;
}

public static string SetBookStrings()
{
string strBookDetails = "";
if (objLibraryBooks.Count > 0)
{
strBookDetails = " Number of Objects requested as of now is " + objLibraryBooks.Count.ToString() +"
"+"Created objects are
";
foreach (KeyValuePair objKvp in objLibraryBooks)
{
strBookDetails += objKvp.Key + "
";
}
}
return strBookDetails;
}
}
}




Default.aspx.cs

using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace LazyInitialzation
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void btnCreate_Click(object sender, EventArgs e)
{
LibraryBooks.GetBooks(txtBookType.Text);
Response.Write(LibraryBooks.SetBookStrings());
}
}
}

Default.aspx








Enter Book to be Created










To Test the code run the asp.net application. Enter book types you wanted to create in the textbox. When you create a book type which already exist the count of objects in the dictionary object does not get increased and the object request is being served from the existing objects.

The entire code for download is available at http://www.csharppatterns.com/

No comments: