http://www.sufeinet.com/plugin.php?id=keke_group

苏飞论坛

 找回密码
 马上注册

QQ登录

只需一步,快速开始

分布式系统框架(V2.0) 轻松承载百亿数据,千万流量!讨论专区 - 源码下载 - 官方教程

HttpHelper爬虫框架(V2.7-含.netcore) HttpHelper官方出品,爬虫框架讨论区 - 源码下载 - 在线测试和代码生成

HttpHelper爬虫类(V2.0) 开源的爬虫类,支持多种模式和属性 源码 - 代码生成器 - 讨论区 - 教程- 例子

查看: 3141|回复: 4

[学习心得] C#单列模式的实现

[复制链接]
发表于 2018-12-29 20:59:31 | 显示全部楼层 |阅读模式
五 、 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 );
}
}




1. 开通SVIP会员,免费下载本站所有源码,不限次数据,不限时间
2. 加官方QQ群,加官方微信群获取更多资源和帮助
3. 找站长苏飞做网站、商城、CRM、小程序、App、爬虫相关、项目外包等点这里
发表于 2018-12-30 18:19:24 | 显示全部楼层
我只是路过打酱油的。
发表于 2018-12-30 20:57:05 | 显示全部楼层
强烈支持楼主ing……
发表于 2018-12-30 21:48:15 | 显示全部楼层
强烈支持楼主ing……
发表于 2018-12-30 22:02:24 | 显示全部楼层
我只是路过打酱油的。
您需要登录后才可以回帖 登录 | 马上注册

本版积分规则

QQ|手机版|小黑屋|手机版|联系我们|关于我们|广告合作|苏飞论坛 ( 豫ICP备18043678号-2)

GMT+8, 2024-5-3 16:36

© 2014-2021

快速回复 返回顶部 返回列表