单例模式
单例模式常见的写法有懒汉模式,饿汉模式,双重检查模式等。
- 懒汉模式就是用的时候再去创建对象。
- 饿汉模式就是提前就已经加载好的静态static对象。
- 双重检查模式就是在加锁前和加锁后共两次检查防止多线程创建多个对象。
单例模式有以下特点:
- 单例类只能有一个实例。
- 单例类必须自己创建自己的唯一实例。
- 单例类必须给所有其他对象提供这一实例。
优点: 不会频繁的创建和销毁对象,浪费系统资源
单线程情况下的单例模式
class Singleton {
private static Singleton instance = null;
private Singleton() {
System.out.println("我是构造方法" + Thread.currentThread().getName());
}
static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public static void main(String[] args) {
Singleton instance1 = Singleton.getInstance(