Using Lazy Loading Design pattern to load data when required

Hi,

Some time when you are working with large objects where some of the data (properties in the object) is not required frequently, the use of Lazy loading is the best.

 Let’s say you have an Object which contains many properties along with a property for exposing long XML string. The long XML string is only required to be shown only a few times when you are also showing the details of the object. At this point when we are loading a list of this object to display (where by XML string will not be displayed) its not a good practice to also load the XML string in the object. Since this would take lots of extra Network bandwidth and memory space.

In these kinds of circumstances we can use the Lazy Loading Object relational pattern. In Lazy loading pattern the object is not inialized until it’s needed. There are many ways to Implement Lazy Loading.

One of the simple way of using Lazy loading is shown below

public class Category
{
    private int _CategoryId = 0;
    private int CategoryId
    {
        set { _CategoryId = value; }
        get { return _CategoryId; }
    }

    private string  _strXML = null;
    public string strXML
    {
        get
        {   

            //This is done for lazy Loading the XML String .
            if (_StrXML == null)
                _StrXML = StrXML.GetStrXMLByCategoryId(_CategoryId);
            return _StrXML;
        }
        set { _StrXML = value; }
    }
}

In the example given above, I am loading the strXML property only when it is being used. The property will not be loaded before that.

Regards
Vikram


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2008 Vikram Lakhotia