设计模式之单例模式示例
程序员文章站
2022-07-13 23:34:34
...
- 饿汉式
/**
*
* @author lxw
*
*饿汉式 ,不使用时创建导致内存浪费,反射能够破坏
*优点,使用时效率高,直接使用不用在创建线程安全
*/
public class PositiveSingleton {
private static PositiveSingleton instance = new PositiveSingleton();
private PositiveSingleton(){
}
public static PositiveSingleton getInstance(){
return instance;
}
}
- 懒汉式
/**
*
* @author lxw
*优点:使用时创建,相对来说不会浪费内存空间
*缺点:多线程情况下,不安全,反射能够破坏
*/
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton(){
}
public static LazySingleton getInstace(){
if (instance == null){
instance = new LazySingleton();
}
return instance;
}
}
/**
*
* @author lxw
*优点:线程安全,不造成内存浪费
*缺点:多线程访问,导致方法阻塞线程,影响效率,反射能够破坏
*/
public class LazyThreadSingleton {
private static LazyThreadSingleton instance;
private LazyThreadSingleton(){}
public synchronized static LazyThreadSingleton getInstance(){
if (instance == null){
instance = new LazyThreadSingleton();
}
return instance;
}
}
/**
*
* @author lxw
*优点:线程安全
*缺点:效率低,反射能够破坏
*/
public class LazyThreadSingletonFunction {
private static LazyThreadSingletonFunction instance;
private LazyThreadSingletonFunction(){}
public static LazyThreadSingletonFunction getInstance(){
synchronized (LazyThreadSingletonFunction.class) {
if (instance == null){
instance = new LazyThreadSingletonFunction();
}
}
return instance;
}
}
/**
*
* @author lxw
*
*优点:线程安全,效率较高
*缺点:不够优雅,反射能够破坏
*/
public class LazyThreadDubboSingleton {
private static LazyThreadDubboSingleton instance;
private LazyThreadDubboSingleton(){}
public static LazyThreadDubboSingleton getInstance(){
if (instance == null){
synchronized (LazyThreadDubboSingleton.class) {
if (instance == null){
instance = new LazyThreadDubboSingleton();
}
}
}
return instance;
}
}
/**
*
* @author lxw
* 优点:线程安全,不浪费内存空间
* 缺点:不优雅, 反射能够破坏
*/
public class StaticInnerClass {
private StaticInnerClass(){}
public static StaticInnerClass getInstance(){
return InnerLazy.instance;
}
private static class InnerLazy {
public static StaticInnerClass instance = new StaticInnerClass();
}
}
/**
*
* @author lxw
*优雅,官方推荐,反射不能破坏
*/
public enum EnumSingleton {
INSTANCE;
private Object data;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public static EnumSingleton getInstance(){
return INSTANCE;
}
}
上一篇: 单例模式示例
下一篇: 设计模式--单例模式示例代码