Singleton 模式的Java和C#的实现方法

看到MSDN对Singleton模式的讲解。对其中的各种实现的代码摘录出来备用。

Singleton 模型非常简单直观。 (通常)只有一个 Singleton 实例。 客户端通过一个已知的访问点来访问 Singleton 实例。 在这种情况下,客户端是一个需要访问唯一 Singleton 实例的对象。
GoF Singleton 实现:
// Declaration
class Singleton {
public:
    static Singleton* Instance();
protected:
    Singleton();
private:
    static Singleton* _instance;
}

// Implementation
Singleton* Singleton::_instance = 0;

Singleton* Singleton::Instance() {
    if (_instance == 0) {
        _instance = new Singleton;
    }
    return _instance;
}
使用 Java 语法的双重检验锁定 Singleton 代码(为了解决多线程应用程序)
// C++ port to Java
class Singleton
{
    public static Singleton Instance() {
        if (_instance == null) {
            synchronized (Class.forName("Singleton")) {
                if (_instance == null) {
                    _instance = new Singleton();
                }
             }
        }
        return _instance;     
    }
    protected Singleton() {}
    private static Singleton _instance = null;
}

以 C# 编码的双重检验锁定
// Port to C#
class Singleton
{
    public static Singleton Instance() {
        if (_instance == null) {
            lock (typeof(Singleton)) {
                if (_instance == null) {
                    _instance = new Singleton();
                }
            }
        }
        return _instance;     
    }
    protected Singleton() {}
    private static volatile Singleton _instance = null;
}
.NET Singleton 示例(使用.net框架来解决各种问题)
// .NET Singleton
sealed class Singleton
{
    private Singleton() {}
    public static readonly Singleton Instance = new Singleton();
}

示例 Singleton 使用
sealed class SingletonCounter {
    public static readonly SingletonCounter Instance =
         new SingletonCounter();
    private long Count = 0;
    private SingletonCounter() {}
    public long NextValue() {
        return ++Count;
    }
}

class SingletonClient {
    [STAThread]
    static void Main() {
        for (int i=0; i<20; i++) {
            Console.WriteLine("Next singleton value: {0}",
                SingletonCounter.Instance.NextValue());
        }
    }
}

参考:
http://www.microsoft.com/china/MSDN/library/enterprisedevelopment/builddistapp/Exploring+the+Singleton+Design+Pattern.mspx

原文地址:https://www.cnblogs.com/echo/p/140416.html