一、懒汉式单例
懒汉式单例,简单点说就是类加载的时候不创建对象,仅仅加载类,实现的几种方式如下:
第一种:
public class LazySingleton {
private LazySingleton(){
}
private static LazySingleton singleton = null;
public LazySingleton getSingleton(){
//判断单例创建情况,确保单例唯一
if(singleton == null){
return new LazySingleton();
}else{
return singleton;
}
}
}
如上代码所述,通过创建私有的构造函数和私立静态的类对象,仅仅对外公开一个 getSingleton() 方法,用于获取实例,再通过对象判断确保实例唯一。
但是,这种只适合在单线程下执行,当多线程下时,就会出现并发的情况。所以我们可以通过 synchronized(不懂的可以看这篇文章) 来实现同步,但是在频繁调用对性能会有些影响,代码如下:
第二种,在执行语句里实现:
public class LazySingleton {
private LazySingleton(){
}
//考虑并发单例,使用synchronized同步执行语句
private static LazySingleton singleton = null;
public LazySingleton getSingleton() {
//通过synchronized保证只有一个进程调用改函数或方法
synchronized (LazySingleton.class) {
if (singleton == null) {
return new LazySingleton();
}else{
return singleton;
}
}
}
}
第三种,在方法里实现:
public class LazySingleton {
private LazySingleton(){
}
//考虑并发单例,使用synchronized同步方法
//直接在方法上实现同步
private static LazySingleton singleton = null;
public static synchronized LazySingleton getSingleton(){
if(singleton == null){
return new LazySingleton();
}else{
return singleton;
}
}
}
第四种,静态内部类实现单例:
public class LazySingleton {
private LazySingleton(){
}
private static class LazySingletonByStatic{
private static final LazySingleton lazySingleton = new LazySingleton();
}
private static final LazySingleton getLazySingleton(){
return LazySingleton.LazySingletonByStatic.lazySingleton;
}
}
在类加载的时候,并不会初创建实例,只有在调用的时候会创建实例
二、饿汉式单例
饿汉式单例,即在类加载的时候就创建好唯一的实例,这样做会占用空间,因为这是在类加载的时候就创建好的,不管是否调用,代码如下:
public class HungrySingleton {
//私有构造函数,避免被外部类调用
private HungrySingleton(){
}
//类加载的时候新建唯一一个私有的内部静态常量
private static final HungrySingleton hungrySingleton = new HungrySingleton();
//对外方法,调用方法获取唯一的对象
public static final HungrySingleton getHungrySingleton(){
return hungrySingleton;
}
}
静态代码块实现单例
代码如下:
public class StaticBlackSingleton {
private static StaticBlackSingleton staticBlackSingleton;
static {
staticBlackSingleton = new StaticBlackSingleton();
}
public static StaticBlackSingleton getStaticBlackSingleton(){
return staticBlackSingleton;
}
}
参考学习连接:
https://blog.csdn.net/u014672511/article/details/79774847