zoukankan      html  css  js  c++  java
  • 单件模式

    特点:
         1:单例类只能有一个实例。
         2:单例类必须自己创建自己的唯一实例。
         3:单例类必须给所有其它对象提供这一实例。

    应用:
          每台计算机可以有若干个打印机,但只能有一个Printer Spooler,避免两个打印作业同时输出到打印机。 
       一个具有自动编号主键的表可以有多个用户同时使用,但数据库中只能有一个地方分配下一个主键编号。否则会出现主键重复。


    代码实现:

    public sealed class Singleton
    {
        Singleton()
        
    {
        }


        
    public static Singleton Instance
        
    {
            
    get
            
    {
                
    return Nested.instance;
            }

        }

        
        
    class Nested
        
    {
            
    // Explicit static constructor to tell C# compiler
            
    // not to mark type as beforefieldinit
            static Nested()
            
    {
            }


            
    internal static readonly Singleton instance = new Singleton();
        }

    }


     

    代码

        /// <summary>
        
    /// 泛型实现单例模式
        
    /// </summary>
        
    /// <typeparam name="T">需要实现单例的类</typeparam>

        public class Singleton<T> where T : new()
        
    {
            
    /// <summary>
            
    /// 返回类的实例
            
    /// </summary>

            public static T Instance
            
    {
                
    get return SingletonCreator.instance; }
            }


            
    class SingletonCreator
            
    {
                
    internal static readonly T instance = new T();
            }

        }

    //某一个类
    public class Test
    {
        
    private DateTime _time;

        
    public Test()
        
    {
            System.Threading.Thread.Sleep(
    3000);
            _time 
    = DateTime.Now;    
        }


        
    public string Time
        
    {
            
    get return _time.ToString(); }
        }

    }

    //调用
            
    // 使用单例模式,保证一个类仅有一个实例
            Response.Write(Singleton<Test>.Instance.Time);
            Response.Write(
    "<br />");
            Response.Write(Singleton
    <Test>.Instance.Time);
            Response.Write(
    "<br />");

            
    // 不用单例模式
            Test t = new Test();
            Response.Write(t.Time);
            Response.Write(
    "<br />");
            Test t2 
    = new Test();
            Response.Write(t2.Time);
            Response.Write(
    "<br />");


    特别提醒的是由于静态方法是线程共享的所以数据库连接字符串不能是静态类型.
     

  • 相关阅读:
    linux里忘记root密码解决办法
    Oracle怎样方便地查看报警日志错误
    清空文件内容
    channel c3 disabled, job failed on it will be run on another channel
    未能启动虚拟电脑,由于下述物理网卡找不到,你可修改虚拟电脑的网络设置或停用之
    DG下手工处理v$archive_gap方法
    Vue.js + Element.ui 从搭建环境到打包部署
    js判断json对象是否为空
    获取 request 中用POST方式"Content-type"是"application/x-www-form-urlencoded;charset=utf-8"发送的 json 数据
    DIV的内容自动换行
  • 原文地址:https://www.cnblogs.com/tommyli/p/1032378.html
Copyright © 2011-2022 走看看