1. 饿汉模式
class SingletonHungary {
//由于只能 new一次 先私有化构造器 通提供方法访问
//static 方法类只能访问 static 属性
private static SingletonHungary singletonHungary = new SingletonHungary();
//将构造器设置为private禁止通过new进行实例化
private SingletonHungary() {
}
// 静态全局化 提供get方法
public static SingletonHungary getInstance() {
return singletonHungary;
}
}
2. 懒汉模式
// 单例模式的懒汉实现1--线程不安全
class SingletonLazy {
private static SingletonLazy singletonLazy;
private SingletonLazy() {
}
public static SingletonLazy getInstance() {
//判断singletonLazy 是否被 new过 new过一次就不会在new新的singletonLazy
if (null == singletonLazy) {
singletonLazy = new SingletonLazy();
}
return singletonLazy;
}
}
3.双锁式
class SingletonLazy{
private static SingletonLazy singletonLazy;//singletonLazy修饰被不同线程访问和修改的变量
private SingletonLazy(){}
public static SingletonLazy getInstance(){
// 先判断实例是否存在,若不存在再对类对象进行加锁处理
if(singletonLazy==null){
synchronized(SingletonLazy.class){//对整个类加锁
if(singletonLazy==null){
singletonLazy=new SingletonLazy();
}
}
}
return singletonLazy;
}
}
4.类部类式
class SingletonHungary {
private SingletonHungary() {
}
private static class SingletonHungary2{
private static SingletonHungary singletonHungary = new SingletonHungary();
}
public static SingletonHungary getInstance() {
return SingletonHungary2.singletonHungary;
}
}