所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法(静态方法)。
(1)饿汉式(静态变量)
class Singleton{
private Singleton(){
}
private final static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
}
(2)饿汉式(静态代码块)
class Singleton2{
private Singleton2(){
}
private static Singleton2 instance ;
static {
instance = new Singleton2();
}
public static Singleton2 getInstance(){
return instance;
}
}
(3)懒汉式(线程不安全,不推荐)
class Singleton3{
private Singleton3(){
}
private static Singleton3 instance ;
public static Singleton3 getInstance(){
if(instance == null){
instance = new Singleton3();
}
return instance;
}
}
(4)懒汉式(线程安全,不推荐)
class Singleton4{
private Singleton4(){
}
private static Singleton4 instance ;
public static synchronized Singleton4 getInstance(){
if(instance == null){
instance = new Singleton4();
}
return instance;
}
}
(5)Double-Check(推荐)
class Singleton5{
private Singleton5(){
}
private static volatile Singleton5 instance ;
public static Singleton5 getInstance(){
if(instance == null){
synchronized (Singleton5.class){
if(instance == null){
instance = new Singleton5();
}
}
}
return instance;
}
}
(6)静态内部类(推荐)
class Singleton6{
private Singleton6(){
}
private static class Singleton6Instance{
private static final Singleton6 instance = new Singleton6();
}
public static Singleton6 getInstance(){
return Singleton6Instance.instance;
}
}
(7)枚举实现单例(推荐)
public class _08_Singleton {
public static void main(String[] args) {
Singleton08 instance = Singleton08.INSTANCE;
}
}
enum Singleton08{
INSTANCE;
}
|