单例设计模式

单例设计模式是面试中经常被问到的问题,今天将单例设计模式进行一个复习

单例设计模式

单例设计模式,一个类只有一个实例化对象,且类的构造方法私有化,单例设计模式有三个特点:

  • 只有一个实例对象;
  • 由类自行创建,构造方法私有化;
  • 提供一个访问单例的全局访问点;

单例类的实现

1.懒汉模式

该模式,类加载时没有生成单例对象,只有第一次调用访问单例的方法才会才会穿件单例对象,代码如下:

package singletonModel;

public class lazySingleton {
	private static volatile lazySingleton instance = null;
	private lazySingleton() {};
	public static lazySingleton getInstance() {
		if(instance == null) {
			instance = new lazySingleton();
		}
		return instance;
	}
}

2.饿汉模式

该模式的特点是,类一旦加载就创建一个单例,代码如下:

package singletonModel;

public class hungrySingleton {
	private static final hungrySingleton instance = new hungrySingleton();
	private hungrySingleton() {};
	public static hungrySingleton getInstance() {
		return instance;
	}
}
原文地址:https://www.cnblogs.com/xxyxt/p/11310607.html