Monday, December 24, 2007

Singleton Pattern (2) Lazy Initialization

Declarative Code - Lazy Initialization (Craig Shoemaker)

"You have a holder for an object or data that is not filled with the contents until the code makes a request to the property or object. Thus the code is "lazy" because the work is not done unless the procedure explicitly requires it. No wasted data access or initialziation here."

Javascript example:

window.onload = Window_Load;

function Window_Load()

{

txtTitle().value = "Title";

}

var mTitle = null;

function txtTitle()

{

if(mTitle == null)

{

mTitle = document.getElementById("txtTitle");

}

return mTitle;

}

C# example:


private Customers mCustomer = null;

private Customers Customer

{

get

{

if(this.mCustomer == null)

{

this.mCustomer = (Customers)ObjectBroker.GetObject(typeof(Customers),primaryKey);

}

return this.mCustomer;

}

}

private void Page_Load(Object sender, System.EventArgs e)

{

this.txtCustomer.Name = this.Customer.Name;

}

blog comments powered by Disqus