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

    作为对象的创建模式,单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类。
    单例模式有以下特点:
    单例类只能有一个实例。
    单例类必须自己创建自己的唯一实例。
    单例类必须给所有其他对象提供这一实例。
    一个典型的单例类的实现如下所示:其中构造子私有表示子类不能被继承
    public class Singleton

          private static Singleton m_instance = null; 
          private Singleton() { } 
          public static Singleton getInstance() 
          { 
                if(m_instance==null) 
                { 
                      m_instance=new Singleton(); 
                } 
                return m_instance; 
          }
    }

    加上多线程的单例模式

    public class Singleton

          private static Singleton m_instance = null; 

      private static object instanceObj = new object();


          private Singleton() { } 
          public static Singleton getInstance() 
          { 
                if(m_instance==null) 
                { 

          lock(instanceObj)

          {

            if(m_instance==null)

            {
                          m_instance=new Singleton(); 

            }

          }
                } 
                return m_instance; 
          }
    }


     

  • 相关阅读:
    平时十二测
    无题十四
    暑假第十测
    无题十三
    noip错题集
    无题十二
    BZOJ整理
    志愿者招募
    修车
    任务安排
  • 原文地址:https://www.cnblogs.com/vihone/p/1547006.html
Copyright © 2011-2022 走看看