August 10, 2010 by Christoff Truter C# Design Patterns Architecture
The singleton pattern basically involves a class that only allows a single
instance of itself to be instantiated.
public sealed class Singleton
{
static Singleton _instance = null;
private Singleton()
{
Console.WriteLine("Instance Created");
}
public static Singleton Instance
{
get
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
}
class Program
{
static void Main()
{
for (int i = 0; i < 10; i++)
{
Thread thread = new Thread(new ThreadStart(ThreadMain));
thread.Start();
}
}
static void ThreadMain()
{
Thread.Sleep(500);
try
{
Singleton s = Singleton.Instance;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
public sealed class Singleton
{
private static volatile Singleton instance;
private static object locker = new Object();
private Singleton()
{
Console.WriteLine("Instance Created");
}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (locker)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
public sealed class Singleton
{
public static readonly Singleton Instance = new Singleton();
static Singleton() { }
private Singleton()
{
Console.WriteLine("Instance Created");
}
}
public sealed class Singleton
{
private static readonly Lazy<Singleton> _instance = new Lazy<Singleton>(() => new Singleton());
private Singleton() { Console.WriteLine("Instance Created"); }
public static Singleton Instance
{
get
{
return _instance.Value;
}
}
}
August 11, 2010 by Christoff Truter
Thanks Andre, hopefully soon I will have a complete list of examples available on all design patterns - started working on a post regarding the factory pattern.