Design Patterns :: Singleton
There are many common situations when singleton pattern is used:
- Accesing resources in shared mode
- Configuration Classes
- Logger Classes
- Serialization
- Network Port Interface
 |
| Singleton Design Pattern |
Check list
1.Define a private static attribute in the "single instance" class.
2.Define a public static accessor function in the class.
3.Do "lazy initialization" (creation on first use) in the accessor function.
4.Define all constructors to be protected or private.
5.Clients may only use the accessor function to manipulate the Singleton.
-
-
namespace DesignPatternsSingleton
-
-
/// MainApp startup class for Design Patterns :: Singleton
-
-
-
-
-
-
-
-
-
private static Singleton _instance;
-
// Constructor is 'protected'
-
-
-
-
public static Singleton Instance()
-
// Uses lazy initialization.
// Note: this is not thread safe.
-
-
_instance = new Singleton();
-
-
-
-
-
-
-
using System.Collections.Generic;
-
-
namespace DesignPatternsSingleton
-
-
/// MainApp startup class for Real-World
/// Singleton Design Pattern.
-
-
-
-
/// Entry point into console application.
-
-
-
LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
LoadBalancer b4 = LoadBalancer.GetLoadBalancer();
-
-
if (b1 == b2 && b2 == b3 && b3 == b4)
-
Console.WriteLine("Same instance\n");
-
-
// Load balance 15 server requests
LoadBalancer balancer = LoadBalancer.GetLoadBalancer();
for (int i = 0; i < 15; i++)
-
string server = balancer.Server;
Console.WriteLine("Dispatch Request to: " + server);
-
-
-
-
-
-
-
-
/// The 'Singleton' class
-
-
-
private static LoadBalancer _instance;
private List<string> _servers = new List<string>();
private Random _random = new Random();
-
// Lock synchronization object
private static object syncLock = new object();
-
// Constructor (protected)
-
-
// List of available servers
-
_servers.Add("ServerII");
_servers.Add("ServerIII");
_servers.Add("ServerIV");
-
-
-
public static LoadBalancer GetLoadBalancer()
-
// Support multithreaded applications through
// 'Double checked locking' pattern which (once
// the instance exists) avoids locking each
// time the method is invoked
-
-
-
-
-
-
_instance = new LoadBalancer();
-
-
-
-
-
-
-
// Simple, but effective random load balancer
-
-
-
-
int r = _random.Next(_servers.Count);
return _servers[r].ToString();
-
-
-
-