Professional Documents
Culture Documents
Advantages :
1. Its saves memory because the single instance is reused again and again.
2. It can be lazy loaded.
3. It helps to hide dependencies.
4. It can be extended into a factory pattern.
Disadvantage :
1. Unit testing is more difficult (because it introduces a global state into an application).
2. Singleton causes code to be tightly coupled.
3. This pattern reduces the potential for parallelism within a program, because to access the
singleton in a mufti-threaded system, an object must be serialized (by locking).
Example
namespace SingletonPattern
{
public sealed class SingleTon
{
private static int counter = 0;
private static readonly object obj = new object();
private SingleTon()
{
counter++;
Console.WriteLine("Counter {0}", counter);
}
return instance;
}
}
namespace SingletonPattern
{
class Program
{
static void Main(string[] args)
{
Parallel.Invoke(
() => FromObject1(),
() => FromObject2()
);
Console.ReadLine();
}