{
// 使用一个类变量缓存曾经创建的实例
private static Singleton instance;
// 将构造器使用private修饰,隐藏该构造器
private Singleton(){}
// 提供一个静态方法,用于返回Singleton实例
// 该方法可以加入自定义的控制,保证只产生一个Singleton对象
public static Singleton getInstance()
{
// 如果instance为null,表明还不曾创建Singleton对象
// 如果instance不为null,则表明已经创建了Singleton对象,将不会执行该方法
if (instance == null)
{
// 创建一个Singleton对象,并将其缓存起来
instance = new Singleton();
}
return instance;
}
}
优点:减少创建java实例所带来的系统开销
会带来线程安全的问题
线程安全的单例模式
- public class Singleton{
- private static Singleton instance=null;
- private Singleton(){}
- public static synchronized Singleton getInstance(){
- if(instance==null){
- instance=new Singleton();
- }
- return instance;
- }
- }
- //懒汉式
- class LSingle{
- private static Instance _instance = null;
- private LSingle(){}
- public static Instance getInstance(){
- if(_instance==null){
- synchronized(LSingle.class){
- _instance = new Instance();
- }
- }
- return _instance;
- }
- }
- //饿汉式
- class ESingle{
- private static Instance _instance = new Instance();
- private ESingle(){}
- public static Instance getInstance(){
- return _instance;
- }
- }