为什么要学单例设计模式?

单例设计模式能够确保整个系统中只存在一个实例,这可以节省内存空间,并且在有些情况下必须要设计为单例的。比如我们对文件的操作,Windows是多进程多线程的系统,多个进程都可以同时操作文件,这就要确保对文件的操作必须通过唯一的实例来处理。还有就是我们的网站计数器,我们必须要让整个网站只有一个网站计数器。还有系统日志也是一样的。

Java中单例模式的代码实现

饿汉式

class Singleton {
    private Signleton(){} // 私有化构造器
    private final static Singleton instance = new Singleton();
    public static Singleton getInstance() { // 提供公共的静态的方法,返回该类的实例
    	return instance;
    }
}

懒汉式

class Singleton {
     private Singleton() {} // 私有化构造器
     private static Singleton instance = null;
     public static Singleton getInstance() {
          if(instance == null) {
               synchroized(Singleton.class) {
                    if(instance == null) {
                         instance = new Singleton();
                    }
               }
          }
          return instance;
     }
}

Q.E.D.


热爱生活,热爱程序