单例模式:只允许一个实例存在的场景,如任务管理器等
单例模式的7种表现形式
1.
/**
* 饿汉式
* 简单实用,线程安全
* 无论是否使用到这个实例,只要类被加载就会创建这个实例,造成空间浪费
* */
public class Demo01 {
private static final Demo01 Instance = new Demo01();
public Demo01(){}
public static Demo01 getInstance(){
return Instance;
}
}
2.
/**
* 饿汉式
* 将实例化放到静态语句块中,线程安全
* 无论是否使用到这个实例,只要类被加载就会创建这个实例,造成空间浪费
* */
public class Demo02 {
private static final Demo02 Instance;
static{
Instance = new Demo02();
}
public Demo02(){}
public static Demo02 getInstance(){
return Instance;
}
}
3.
/**
* 懒汉式
* 实现了懒加载,只有调用getInstance()方法时才会创建实例
* 多线程访问时,有可能出现多个实例的情况(线程的安全性)
* */
public class Demo03 {
private static Demo03 Instance;
private Demo03(){}
public static Demo03 getInstance(){
if(Instance ==null){
Instance = new Demo03();
}
return Instance;
}
}
4.
/**
* 懒汉式
* 实现了懒加载,只有调用getInstance()方法时才会创建实例
* 通过synchronized实现线程安全,效率大大降低
* */
public class Demo04 {
private static Demo04 Instance;
private Demo04(){}
public static synchronized Demo04 getInstance(){
if(Instance ==null){
Instance = new Demo04();
}
return Instance;
}
}
5.
/**
* 懒汉式
* 实现了懒加载,只有调用getInstance()方法时才会创建实例
* 通过synchronized实现线程安全,同时缩小同步代码块的范围
* */
public class Demo05 {
private static Demo05 Instance;
private Demo05(){}
public static synchronized Demo05 getInstance(){
if(Instance ==null){
synchronized (Demo05.class){
//需要双重判断
if(Instance==null){
Instance = new Demo05();
}
}
}
return Instance;
}
}
6.
/**
* 懒汉式
* 实现了懒加载,通过静态内部类的方式(加载外部类的时候不会加载内部类)
* */
public class Demo06 {
private Demo06(){}
private static class Demo06Instace{
private static final Demo06 Instance = new Demo06();
}
public static Demo06 getInstance(){
return Demo06Instace.Instance;
}
}
7.
/**
* 通过枚举的方式实现单例
* 线程安全且高效
* */
public enum Demo07 {
INSTANCE;
}