Changes

Jump to: navigation, search

Singleton

1,398 bytes added, 09:52, 2 April 2007
Sample Code
Singleton pattern in C#:
<pre>
class // Singletonpattern -- Real World example  using System;using System.Collections;using System.Threading; namespace DoFactory.GangOfFour.Singleton.RealWorld
{
private static Singleton instance; // MainApp test application
// Note: Constructor is 'protected' protected Singleton() class MainApp
{
static void Main()
{
LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
LoadBalancer b4 = LoadBalancer.GetLoadBalancer();
 
// Same instance?
if (b1 == b2 && b2 == b3 && b3 == b4)
{
Console.WriteLine("Same instance\n");
}
 
// All are the same instance -- use b1 arbitrarily
// Load balance 15 server requests
for (int i = 0; i < 15; i++)
{
Console.WriteLine(b1.Server);
}
 
// Wait for user
Console.Read();
}
}
public static // "Singleton Instance()"   class LoadBalancer
{
private static LoadBalancer instance; private ArrayList servers = new ArrayList();  private Random random = new Random();  // Use 'Lazy initialization' Lock synchronization object if private static object syncLock = new object();  // Constructor (protected) protected LoadBalancer(instance == null)
{
// List of available servers servers.Add("ServerI"); servers.Add("ServerII"); servers.Add("ServerIII"); servers.Add("ServerIV"); servers.Add("ServerV"); }  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 if (instance == null) { lock (syncLock) { if (instance == null) { instance = new SingletonLoadBalancer(); } } }  return instance;
}
return instance; }}</pre>/ Simple, but effective random load balancer Singleton pattern in PHP 5:<pre> public string Server<?phpclass Singleton { // object instance get static $instance; private function __construct() {} private function __clone int r = random.Next(servers.Count) {}; public static function getInstance return servers[r].ToString() { if (!Singleton::$instance instanceof self) {; Singleton::$instance = new self();}
}
return Singleton::$instance;
}
}?>
</pre>
1
edit

Navigation menu