1、应用场景:servelet,spring中的bean 常量,连接池等
2、优缺点:节约内存,重复利用。缺点:线程安全问题
3、创建单例的几种方式:(1)、饿汉式(2)、懒汉式(3)、静态内部方式(4)、枚举(5)、双重检测锁机制
4、饿汉式:
//饿汉式
public class SingletonDemo01 {
// 类初始化时,会立即加载该对象,线程天生安全,调用效率高
private static SingletonDemo01 singletonDemo01 = new SingletonDemo01();
private SingletonDemo01() {
System.out.println("SingletonDemo01初始化");
}
public static SingletonDemo01 getInstance() {
System.out.println("getInstance");
return singletonDemo01;
}
}
// 静态内部类
public class SingletonDemo03 {
private SingletonDemo03() {
System.out.println("初始化..");
}
public static class SingletonClassInstance {
private static final SingletonDemo03 singletonDemo03 = new SingletonDemo03();
}
public static SingletonDemo03 getInstance() {
System.out.println("getInstance");
return SingletonClassInstance.singletonDemo03;
}
}
//懒汉式
public class SingletonDemo02 {
//类初始化时,不会初始化该对象,真正需要使用的时候才会创建该对象。
private static SingletonDemo02 singletonDemo02;
private SingletonDemo02() {
}
public synchronized static SingletonDemo02 getInstance() {
if (singletonDemo02 == null) {
singletonDemo02 = new SingletonDemo02();
}
return singletonDemo02;
}
}
// 枚举
enum UserEnum {
HTTP_200(200, "请求成功"),HTTP_500(500,"请求失败");
private Integer code;
private String name;
UserEnum(Integer code, String name) {
this.code = code;
this.name = name;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}}