1、饿汉式
1)简单的饿汉式:
Public class ehanshiSingleton{
Private ehanshiSingleton(){
}
Private final static ehanshiSingleton h = new ehanshiSingleton();
Public static ehanshiSingleton getSingleton(){
Return lhanshiSingleton.h;
}
}
2)静态代码写法:
Public class ehanshiSingleton{
Private ehanshiSingleton(){
}
Private final static ehanshiSingleton h;
Static{
h=ehanshiSingleton();
}
Public static ehanshiSingleton getSingleton(){
Return lhanshiSingleton.h;
}
}
以上两种写法执行是一样的,在类初始化是建立一个对象,当调用静态方法时返回同一个对象的实例,符合单例设计的设计思想,如使用较多的情况下会消耗很多资源;有些单例类使用较少,造成资源浪费;
2、懒汉式
1)简单的懒汉式:
Public class lhanshiSingleton{
Private lhanshiSingleton(){
}
Private static lhanshiSingleton lanhanshiSingleton;
Public static lhanshiSingleton getSingleton(){
If(lanhanshiSingleton==null){
Return new lhanshiSingleton();
}
Return lanhanshiSingleton;
}
}
2)加锁后的懒汉式:
Public class lhanshiSingleton{
Private lhanshiSingleton(){
}
Private static lhanshiSingleton lanhanshiSingleton;
Public static synchronized lhanshiSingleton getSingleton(){
If(lanhanshiSingleton==null){
Return new lhanshiSingleton();
}
Return lanhanshiSingleton;
}
}
3)双重检查锁懒汉式:
Public class lhanshiSingleton{
Private lhanshiSingleton(){
}
Private static lhanshiSingleton lanhanshiSingleton;
Public static lhanshiSingleton getSingleton(){
Synchronized(lhanshiSingleton.class){
If(lanhanshiSingleton==null){
Return new lhanshiSingleton();
}
}
Return lanhanshiSingleton;
}
}
以上便是单例模式的基本写法;