单例模式:
在应用这个模式时单例对象必须保证只有一个实例存在。
思路:
一个类返回同一个对象的引用,和一个获取该实例的静态方法。
需要注意:
单例模式在多线程应用场景下要小心使用;
使用时不能使用反射模式创建实例,否则会实例化一个新的对象。
package Singleton;
public class SingletonTest {
private static SingletonTest instance = null;
private SingletonTest() {
}
private static synchronized void syncInit() {
if (instance == null) {
instance = new SingletonTest();
}
}
public static SingletonTest getInstance() {
if (instance == null) {
syncInit();
}
return instance;
}
}

1588

被折叠的 条评论
为什么被折叠?



