c#

位置:IT落伍者 >> c# >> 浏览文章

C# “Singleton” 模式四种实现方法


发布日期:2020年04月10日
 
C# “Singleton” 模式四种实现方法

大家一定用过或者看过Singleton模式了吧

下面给出三种实现方法分别给出优缺点

方法一

public sealed class Singleton

{

private static readonly Singleton instance = new Singleton();

private Singleton(){}

public static Singleton Instance

{

get

{

return instance;

}

}

}

优点简单明了

缺点耗费资源

方法二

public sealed class ClassicSingleton

{

private static ClassicSingleton instance;

private static object syncRoot = new Object();

private ClassicSingleton() { }

public static ClassicSingleton Instance

{

get

{

if (instance == null)

{

lock (syncRoot)

{

if (instance == null)

{

//custom code

instance = new ClassicSingleton();

}

}

}

return instance;

}

}

}

优点节省资源

缺点代码冗长

方法三

public sealed class Singleton

{

static Singleton(){Instance = new Singleton();}

private Singleton(){}

public static Singleton Instance{get; private set;}

}

优点既节省资源又简单明了

缺点线程不安全

方法四

public class Singleton

{

private static Singleton instance;

// Added a static mutex for synchronising use of instance

private static SystemThreadingMutex mutex;

private Singleton() { }

static Singleton()

{

instance = new Singleton();

mutex = new SystemThreadingMutex();

}

public static Singleton Acquire()

{

mutexWaitOne();

return instance;

}

// Each call to Acquire() requires a call to Release()

public static void Release()

{

mutexReleaseMutex();

}

}

优点既节省资源又简单明了线程也安全了(一箭三雕)

缺点轻微冗长

上一篇:微软明年1月份出台.NET专业开发考试

下一篇:微软发布.Net Framework函数库源码