GOF pattern - Singleton

Definition
Ensure a class has only one instance and provide a global point of access to it.

Frequency of use: use_high.gif high
UML class diagram
singleton.gif
Participants
The classes and/or objects participating in the Singleton pattern are:
  • Singleton (LoadBalancer)
    • defines an Instance operation that lets clients access its unique instance. Instance is a class operation.
    • responsible for creating and maintaining its own unique instance.
Sample code
This structural code demonstrates the Singleton pattern which assures only a single instance (the singleton) of the class can be created.
// Singleton pattern -- Structural example

//--------------------------------------------------------
// Copyright (C) 2001 - 2002, Data & Object Factory
// All rights reserved. www.dofactory.com
//
// You are free to use this source code in your 
// applications as long as the original copyright
// notice is included.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT 
// WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, 
// INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF 
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
//--------------------------------------------------------

using System;

// "Singleton"
class Singleton {
  
// Fields
  private static Singleton instance;

  
// Constructor
  protected Singleton() {}

  
// Methods
  public static Singleton Instance() {
    
// Uses "Lazy initialization"
    if( instance == null )
      instance 
= new Singleton();

    
return instance;
  }
}

/// <summary>
///  Client test
/// </summary>
public class Client {
  
public static void Main() {
    
// Constructor is protected -- cannot use new
    Singleton s1 = Singleton.Instance();
    Singleton s2 
= Singleton.Instance();

    
if( s1 == s2 )
      Console.WriteLine( 
"The same instance" );

    Console.Read();
  }
}
A .NET specificed implementation:
sealed class Singleton {
       
private Singleton();

       
public static readonly Singleton Instance = new Singleton();
}
This real-world code demonstrates the Singleton pattern as a LoadBalancing object. Only a single instance (the singleton) of the class can be created because servers may dynamically come on- or off-line and every request must go throught the one object that has knowledge about the state of the (web) farm.
// Singleton pattern

//--------------------------------------------------
// Copyright (C) 2001, Data & Object Factory
// All rights reserved. www.dofactory.com
//
// You are free to use this source code in your
// applications, although it is intended only for
// educational purposes.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS"
// WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR
// FITNESS FOR A PARTICULAR PURPOSE.
//--------------------------------------------------

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

    Console.Read();
  }
}

posted on 2005-07-07 08:38 毒菇求Buy 阅读(175) 评论(0)  编辑 收藏 引用 所属分类: Design PatternC#

只有注册用户登录后才能发表评论。
<2019年11月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

导航

统计

常用链接

留言簿(7)

随笔分类(133)

随笔档案(111)

文章分类(65)

文章档案(53)

相册

收藏夹(30)

BLOG

Book store

Graphics Design

搜索

最新评论

阅读排行榜

评论排行榜