1、懒汉式单例实例:
package com;
/**
* 懒汉式单利模式 懒汉式单例类.在第一次调用的时候实例化
*/
public class SingleDemo3 {
private static SingleDemo3 uniqueInstance = null;
private String name;
private SingleDemo3() {
System.out.println("我是谁?");
}
public static SingleDemo3 getInstance() {
if (uniqueInstance != null) {
return uniqueInstance;
}
synchronized (SingleDemo3.class) {
if (uniqueInstance == null) {
uniqueInstance = new SingleDemo3();
}
}
return uniqueInstance;
}
}
2、饿汉式单例
package com;
/**
* 饿汉式单利模式
* 饿汉式单例类.在类初始化时,已经自行实例化
*/
public class SingleDemo4 {
private static final SingleDemo4 uniqueInstance = new SingleDemo4();
private SingleDemo4() {
}
public static SingleDemo4 getInstance() {
return uniqueInstance;
}
}