java单例模式可以保证对象的唯一性
1. //懒汉式单例类.在第一次调用的时候实例化自己
2. public class Singleton {
3. private Singleton() {} //私有的构造函数
4. private static Singleton single=null;
5. //静态工厂方法
6. public static Singleton getInstance() {
7. if (single == null) {
8. single = new Singleton();
9. }
10. return single;
11. }
12. }
13. 懒汉式单例的实现没有考虑线程安全问题,它是线程不安全的,并发环境下很可能出现多个Singleton实例
14. 在getInstance方法上加同步
15.
[java] view plain copy
1. public static synchronized Singleton getInstance() {
2. if (single == null) {
3. single = new Singleton();
4. }
5. return single;
6. }
16.
17. 2、双重检查锁定
18.
[java] view plain copy
1. public static Singleton getInstance() {
2. if (singleton == null) {
3. synchronized (Singleton.class) {
4. if (singleton == null) {
5. singleton = new Singleton();
6. }
7. }
8. }
9. return singleton;
10. }
19. 3、静态内部类
20.
[java] view plain copy
1. public class Singleton {
2. private static class LazyHolder {
3. private static final Singleton INSTANCE = new Singleton();
4. }
5. private Singleton (){}
6. public static final Singleton getInstance() {
7. return LazyHolder.INSTANCE;
8. }
9. }
1. //饿汉式单例类.在类初始化时,已经自行实例化
2. public class Singleton1 {
3. private Singleton1() {}
4. private static final Singleton1 single = new Singleton1(); //定义成常量...
5. //静态工厂方法
6. public static Singleton1 getInstance() {
7. return single;
8. }
9. }