using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sigleton
{
/// <summary>
/// 单例类必须只有一个实例
/// 单例类必须自己创建自己的唯一实例
/// 单例类必须给所有其他对象提供这个唯一实例
/// </summary>
class Singleton
{
private static Singleton instance;
protected Singleton()
{}
public static Singleton GetInstance()
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
为产生唯一实例,构造函数私有化,不允许外部New对象。
客户端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sigleton
{
class Client1
{
static void Main(string[] args)
{
Singleton s1 = Singleton.GetInstance();
Singleton s2 = Singleton.GetInstance();
if (s1.Equals(s2))
{
Console.WriteLine("s1==s2");
}
else
{
Console.WriteLine("s1!=s2");
}
Console.Read();
}
}
}
改进之后实际运用:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace SingletonApp
{
/// <summary>
/// 负载均衡类类,
/// 在负载均衡模型中,有多台服务器可供服务,任务分配随机挑选一台服务器提供服务,以确保任务均衡。
/// </summary>
class LoadBalancer
{
//字段
private static LoadBalancer balancer;
private ArrayList servers = new ArrayList();
private Random random = new Random();
//构造方法
protected LoadBalancer()
{
servers.Add("serverI");
servers.Add("serverII");
servers.Add("serverIII");
servers.Add("serverIV");
servers.Add("serverV");
}
/// <summary>
/// 返回类的单一实例
/// </summary>
/// <returns></returns>
public static LoadBalancer GetLoadBalancer()
{
if (balancer == null)
{
Mutex mutex = new Mutex();
if (balancer == null)
{
balancer = new LoadBalancer();
mutex.Close();
}
}
return balancer;
}
public string Server
{
get
{
int r = random.Next(servers.Count);
return servers [r].ToString ();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SingletonApp
{
class SingletonApp
{
static void Main(string[] args)
{
LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
LoadBalancer b4 = LoadBalancer.GetLoadBalancer();
Console.WriteLine(b1.Server);
Console.WriteLine(b2.Server);
Console.WriteLine(b3.Server);
Console.WriteLine(b4.Server);
Console.ReadKey();
}
}
}