单例模式

1.    定义

        保证一个类仅有一个实例,并提供一个访问它的全局访问点。

2.      UML 类图

 

3.      结构代码

// Singleton pattern -- Structural example

using System;

 

namespace DoFactory.GangOfFour.Singleton.Structural

{

  /// <summary>

  /// MainApp startup class for Structural

  /// Singleton Design Pattern.

  /// </summary>

  class MainApp

  {

    /// <summary>

    /// Entry point into console application.

    /// </summary>

    static void Main()

    {

      // Constructor is protected -- cannot use new

      Singleton s1 = Singleton.Instance();

      Singleton s2 = Singleton.Instance();

 

      // Test for same instance

      if (s1 == s2)

      {

        Console.WriteLine("Objects are the same instance");

      }

 

      // Wait for user

      Console.ReadKey();

    }

  }

 

  /// <summary>

  /// The 'Singleton' class

  /// </summary>

  class Singleton

  {

    private static Singleton _instance;

 

    // Constructor is 'protected'

    protected Singleton()

    {

    }

 

    public static Singleton Instance()

    {

      // Uses lazy initialization.

      // Note: this is not thread safe.

      if (_instance == null)

      {

        _instance = new Singleton();

      }

 

      return _instance;

    }

  }

}


Output
Objects are the same instance

4.      实例代码

// Singleton pattern -- Real World example

using System;

using System.Collections.Generic;

using System.Threading;

 

namespace DoFactory.GangOfFour.Singleton.RealWorld

{

  /// <summary>

  /// MainApp startup class for Real-World

  /// Singleton Design Pattern.

  /// </summary>

  class MainApp

  {

    /// <summary>

    /// Entry point into console application.

    /// </summary>

    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");

      }

 

      // 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);

      }

 

      // Wait for user

      Console.ReadKey();

    }

  }

 

  /// <summary>

  /// The 'Singleton' class

  /// </summary>

  class LoadBalancer

  {

    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)

    protected LoadBalancer()

    {

      // 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 LoadBalancer();

          }

        }

      }

 

      return _instance;

    }

 

    // Simple, but effective random load balancer

    public string Server

    {

      get

      {

        int r = _random.Next(_servers.Count);

        return _servers[r].ToString();

      }

    }

  }

}


Output
Same instance

ServerIII
ServerII
ServerI
ServerII
ServerI
ServerIII
ServerI
ServerIII
ServerIV
ServerII
ServerII
ServerIII
ServerIV
ServerII
ServerIV

该文章来自:http://www.dofactory.com/Patterns/PatternSingleton.aspx

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值