Created
June 17, 2014 06:21
-
-
Save EifelMono/daab4911a0009c950ce6 to your computer and use it in GitHub Desktop.
Instance, SingleInstance, MultiInstance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Text; | |
namespace EifelMono | |
{ | |
public class Instance<T> | |
{ | |
public Instance() | |
{ | |
} | |
public Instance(CreateDelegate onCreateInstance) | |
: this() | |
{ | |
OnCreateInstance = onCreateInstance; | |
} | |
public delegate T CreateDelegate(); | |
public CreateDelegate OnCreateInstance = null; | |
public bool AllwaysCreateNewInstance = false; | |
protected T m_Value = default(T); | |
public bool IsValueCreated | |
{ | |
get | |
{ | |
return m_Value != null; | |
} | |
} | |
protected T CreateInstance() | |
{ | |
try | |
{ | |
return OnCreateInstance != null ? OnCreateInstance() : Activator.CreateInstance<T>(); | |
} | |
catch (Exception ex) | |
{ | |
Log.HandleException(ex); | |
return default(T); | |
} | |
} | |
public T Value | |
{ | |
get | |
{ | |
if (AllwaysCreateNewInstance) | |
m_Value = CreateInstance(); | |
else | |
if (!IsValueCreated) | |
m_Value = CreateInstance(); | |
return m_Value; | |
} | |
} | |
} | |
public class SingleInstance<T> : Instance<T> | |
{ | |
public SingleInstance() | |
: base() | |
{ | |
AllwaysCreateNewInstance = false; | |
} | |
public SingleInstance(CreateDelegate onCreateInstance) | |
: base(onCreateInstance) | |
{ | |
AllwaysCreateNewInstance = false; | |
} | |
} | |
public class MultiInstance<T> : Instance<T> | |
{ | |
public MultiInstance() | |
: base() | |
{ | |
AllwaysCreateNewInstance = true; | |
} | |
public MultiInstance(CreateDelegate onCreateInstance) | |
: base(onCreateInstance) | |
{ | |
AllwaysCreateNewInstance = true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment