public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
retun instance;
}
}
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance () {
if (instance == null) {
instatnce = new Singleton();
}
return instance;
}
}
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static synchronized Singleton getInstance () {
if (instance == null) {
instatnce = new Singleton();
}
return instance;
}
}
public class Singleton {
private static Singleton instance = null;
private Singleton {
}
public static Singleton getInstance () {
// If already initialized, no need to get lock everytime.
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance ;
}
}
public class Singleton() {
private Singleton() {
}
public static Singleton getInstance () {
return SingletonHolder.instance;
}
/**
* 静态内部类,只有在装载该内部类时才会去创建单例对象
*/
private static class SingletonHolder {
private static final Singleton instance = new Singleton();
}
}
public enum Singleton {
// 定义一个枚举的元素,它就是Singleton的一个实例
INSTANCE;
public void doSomethig() {
// TODO:
}
}
Singleton singleton = Singleton.INSTANCE; singleton.doSomething();
public class SingletonManager {
private static Map<String, Object> objMap = new HashMap<>();
private Singleton() {
}
public static void addSingleton(String key, Object instance) {
if (!objMap.containsKey(key)) {
objMap.put(key, instance);
}
}
public static getSingleton(String key) {
return objMap.get(key);
}
}
Android设计模式之单例模式(Singleton Pattern)
原文:http://www.cnblogs.com/warmwei818/p/5350837.html