五 、 Singleton 模式在实际系统中的实现
下面这段 Singleton 代码演示了负载均衡对象。在负载均衡模型中,有多台服务器可提供服务,任务分配器随
机挑选一台服务器提供服务,以确保任务均衡(实际情况比这个复杂的多)。这里,任务分配实例只能有一个,
负责挑选服务器并分配任务。
[C#] 纯文本查看 复制代码 // Singleton pattern -- Real World example
using System;
using System.Collections;
using System.Threading;
// "Singleton"
class LoadBalancer
{
// Fields
private static LoadBalancer balancer;
private ArrayList servers = new ArrayList();
private Random random = new Random();
// Constructors (protected)
protected LoadBalancer()
{
// List of available servers
servers.Add( "ServerI" );
servers.Add( "ServerII" );
servers.Add( "ServerIII" );
servers.Add( "ServerIV" );
servers.Add( "ServerV" );
}
// Methods
public static LoadBalancer GetLoadBalancer()
{
// Support multithreaded applications through
// "Double checked locking" pattern which avoids
// locking every time the method is invoked
if( balancer == null )
{
// Only one thread can obtain a mutex
Mutex mutex = new Mutex();
mutex.WaitOne();
if( balancer == null )
balancer = new LoadBalancer();
mutex.Close();
}
return balancer;
}
// Properties
public string Server
{
get
{
// Simple, but effective random load balancer
int r = random.Next( servers.Count );
return servers[ r ].ToString();
}
}
}
/// <summary>
/// SingletonApp test
/// </summary>
///
public class SingletonApp
{
public static void Main( string[] args )
{
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" );
// Do the load balancing
Console.WriteLine( b1.Server );
Console.WriteLine( b2.Server );
Console.WriteLine( b3.Server );
Console.WriteLine( b4.Server );
}
}
|