设计模式

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

2.双重检查版:

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

3.简洁版:

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

4.枚举版:

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

参考:
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