Java进阶-单例模式

单例模式——为了保证 JVM 中某一个类型的 Java 对象永远只有一个,节省内存的开销

单例模式要领

  1. 构造方法私有化
  2. 对外提供一个公开的静态的获取当前类型对象的方法
  3. 提供一个当前类型的静态变量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Singleton { // 懒汉式单例
// 静态变量
private static Singleton s;

// 将构造方法私有化
private Singleton() {}

// 对外提供一个公开获取 Singleton 对象的方法
public static Singleton getInstance() {
if (s == null) {
s = new Singleton();
}
return s;
}
}

public class UserTest {
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2);
}
}

分类

  1. 饿汉式:在类加载阶段就创建了对象
  2. 懒汉式:用到对象的时候才会创建对象
1
2
3
4
5
6
7
8
9
10
11
12
13
// 饿汉式
public class Customer {
// 类加载时只执行一次
private static Customer c = new Customer();

//构造方法私有化
private Customer(){}

// 提供公开的方法
public static Customer getInstance() {
return c;
}
}

缺点

没有子类,无法被继承

1
2
3
4
5
6
7
8
public class Servelet {
// 构造方法私有
private Servelet(){}
}

class HttpServlet extends Servlet {

}