设计模式

  1. singleton pattern 单例模式
    1.基础版:
1
2
3
4
5
6
7
8
9
10
11
12
public class ClassicSingleton {
	private static ClassicSingleton instance = null;
	protected ClassicSingleton() {
		// Exists only to defeat instantiation.
	}
	public static ClassicSingleton getInstance() {
		if(instance == null) {
			instance = new ClassicSingleton();
		}
		return instance;
	}
}

2.双重检查版:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Singleton {
	private static Singleton instance = null;
	protected Singleton() {
		// Exists only to defeat instantiation.
	}
	public static Singleton getInstance() {
		if(singleton == null) {
			synchronized(Singleton.class) {
				if(singleton == null) {
					singleton = new Singleton();
				}
			}
		}
		return singleton;
	}
}

3.简洁版:

1
2
3
4
5
6
public class SimpleSingleton {
	public final static SimpleSingleton INSTANCE = new SimpleSingleton();
	private SimpleSingleton() {
		// Exists only to defeat instantiation.
	}
}

4.枚举版:

1
2
3
4
5
6
public enum EnumSingleton {
    INSTANCE;
    public void someOtherMethod() {
        //
	}
}

参考:
http://www.javaworld.com/article/2073352/core-java/simply-singleton.html
http://www.blogjava.net/kenzhh/archive/2013/03/15/357824.html



blog comments powered by Disqus

Published

05 September 2015

Category

tech_world

Tags