C#实现单件模式的三种常用方法
程序员文章站
2023-11-27 12:47:16
本文实例讲述了c#实现单件模式的三种常用方法。分享给大家供大家参考。具体分析如下:
单件模式是一种设计模式,即保持同时只能创建一个实例,下面列出了c#实现单件模式的三种方...
本文实例讲述了c#实现单件模式的三种常用方法。分享给大家供大家参考。具体分析如下:
单件模式是一种设计模式,即保持同时只能创建一个实例,下面列出了c#实现单件模式的三种方法
方法1
public sealed class singleton { private static readonly singleton instance = new singleton(); private singleton(){} public static singleton instance { get { return instance; } } }
方法2
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) { instance = new classicsingleton (); } } } return instance; } } }
方法3
public class singleton { private static singleton instance; // added a static mutex for synchronising use of instance. private static system.threading.mutex mutex; private singleton(){} static singleton () { instance = new singleton(); mutex = new system.threading.mutex(); } public static singleton acquire() { mutex.waitone (); return instance; } // each call to acquire () requires a call to release() public static void release() { mutex.releasemutex(); } }
希望本文所述对大家的c#程序设计有所帮助。