单例模式

Posted by t298 on April 29, 2021

什么是单例模式?

就是程序在运行时,一个类只有一个对象。那为什么要用单例模式呢?因为有的类比较庞大并且复杂,如果频繁的创建和销毁对象,对资源来说也是一种浪费。比如链接数据库时创建的链接对象,我们只需要创建一个,每次用的时候去用就行。

实现

  1. 这种加载方式为“懒加载”,只有第一次调用时,对象才会被加载。比较省资源但是线程是不安全的。
1
2
3
4
5
6
7
8
9
10
public class Test{
    private Test(){} //构造器私有
    private  static Test instance = null; //初始化对象为null
    public static Test getInstance(){
        if (instance == null){
            instance = new Test();
        }
        return instance;
    }
}
  1. 这种写法虽然是线程安全的,但却不是懒加载的。
1
2
3
4
5
6
7
public class Test{
    private  static Test instance = new Test(); 
    private Test(){}
    public static Test getInstance(){
        return instance;
    }
    }
  1. 匿名内部类
1
2
3
4
5
6
7
8
9
public class Test{
    private static class Testholder{
        private static final Test INSTANCE = new Test();
    }
    private Test(){}
        public static final Test getInstance(){
        return Testholder.INSTANCE;
        }
    }
  1. 反射可以破换上面说的几种方法,还要防止反射,只能用枚举了。但是没有办法懒加载。
1
2
3
4
public enum Test {
    INSTANCE;
    }