饿汉式
public class Singleton{
//直接创建对象
public static Singleton innstance = new Singleton();
//私有化构造函数
private Singleton(){
}
//返回对象实例
public static Singleton getInstance(){
return instance;
}
}
懒汉式
public class Singleton(){
//声明变量
private static volatile Singleton singleton = null;
//私有构造函数
private Singleton(){
}
public static Singleton getInstace(){
if (singleton == null ){
synchronized (Singleton.class){
if (singleton == null){
singleton =new Singleton();
}
}
}
return singleton;
}
}