单例模式

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

懒汉式单例:

public class Singleton {
 2     //私有的默认构造函数
 3     private Singleton(){
 4         
 5     }
 6     private static Singleton instance = null;
 7     //静态工厂方法
 8     public static Singleton getInstance(){
 9         if(instance==null)
10             instance = new Singleton();
11         return instance;
12     }
13 }

Singleton通过将构造方法限定为private避免了类在外部被实例化,在同一个虚拟机范围内,Singleton的唯一实例只能通过getInstance()方法访问。

原文地址:https://www.cnblogs.com/Akke/p/4619861.html