赞
踩
1、饿汉式(先创建出实例):
class Singleton{
//静态实例
private static Singleton singleton = new Singleton();
//构造函数
private Singleton(){};
public Singleton getInstance(){
return singleton;
}
}
2、懒汉式(需要时才创建实例):
class Singleton{
private static Singleton singleton = null;
public static synchronized Singleton getInstance(){
if(null == singleton){
singleton = new Singleton();
}
return singleton;
}
}
3、枚举
enum Singleton{
INSTANCE; //枚举成员
private Singleton singleton;
private Singleton{
singleton = new Singleton();
}
public Singleton getInstance(){
return singleton;
}
}
//获得实例:Singleton.INSTANCE.getInstance();
4、静态内部类:
class Singleton{
//静态内部类
private static calss SingletonHolder{
private static final Singleton singleton = new Singleton();
}
//构造函数
private Singleton(){};
public static final Singleton getInstance(){
return SingletonHolder.singleton;
}
}
5、静态代码块
class Singleton{
//静态变量
private static Singleton singleton = null;
//构造函数
private Singleton(){};
//静态代码块
static{
singleton = new Singleton();
}
public Singleton getInstance(){
return singleton;
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。