Hi Everyone,
Today I want to discuss one simple pattern "Initialization on user request". I name it simply: lazy initialization. I will not describe pattern, lets code talk for itself.
First several simple declarations of usefull utility classes: Generic EventArgs.
/// <summary></summary>
/// <typeparam name="T"></typeparam>
public class EventArgs<T> : EventArgs where T : class
{
#region Class members
/// <summary></summary>
private T m_data;
#endregion
#region Class properties
/// <summary></summary>
public T Data
{
get
{
return m_data;
}
set
{
m_data = value;
}
}
#endregion
#region Class constructor
/// <summary></summary>
public EventArgs()
: this( null )
{
}
/// <summary></summary>
/// <param name="data"></param>
public EventArgs( T data )
{
m_data = data;
}
#endregion
}
Second one is simple Cache control interface:
/// <summary>Inheritance of this interface showing that class implements
/// caching pattern and allowing user reset of caches.</summary>
public interface ICacheSupporting
{
/// <summary>
/// Force cleanup of internal caches. Reset internal caches.
/// </summary>
void ResetCaches();
}
And at last our pattern code:
/// <summary>Lazy initialization pattern implementation.</summary>
/// <typeparam name="T"></typeparam>
public class LazyValue<T> : ICacheSupporting
where T : class
{
#region Class members
/// <summary></summary>
private T m_value;
/// <summary></summary>
private EventHandler<EventArgs<T>> m_getValue;
#endregion
#region Class properties
/// <summary>Get value for real job.</summary>
public T Value
{
get
{
// if value not initialized yet then call delegate
if( m_value == null )
{
EventArgs<T> args = new EventArgs<T>( null );
m_getValue( this, args );
m_value = args.Data;
}
return m_value;
}
}
#endregion
#region Class intialize
/// <summary>Initialize lazy initialization pattern by delegate that
/// will create instance of data for us.</summary>
/// <param name="getter">delegate that will create instance of data.</param>
public LazyValue( EventHandler<EventArgs<T>> getter )
{
if( getter == null )
throw new ArgumentNullException( "getter" );
m_getValue = getter;
}
#endregion
#region Class public methods
/// <summary>Reset cached internally value.</summary>
public void ResetCaches()
{
m_value = null;
}
#endregion
}
And always asked question: how to use it?!
using StringsDictionary = Dictionary<string,string>;
/// <summary>Udf ID - to - User Defined Field Name</summary>
private LazyValue<StringsDictionary> m_cacheUdfs = new LazyValue<StringsDictionary>(
delegate( object sender, EventArgs<StringsDictionary> e )
{
e.Data = new StringsDictionary();
}
);
protected virtual StringsDictionary UserDefinedNamesCache
{
get
{
return m_cacheUdfs.Value;
}
}
Enjoy. Now it's much easier to make "lazy initilization" in applications.
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5