/**
* @project: JavaTest
* @description : 单倒模式
* @author: jim.sun Credited: 2013-4-11
* @modify_time: 2013-4-11
*/
public class SingletonTest {
public static void main(String[] args) {
// 创建Singleton 对象不能通过构造器,只能通过getInstance方法
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
// 将输出true;
System.out.println(s1 == s2);
}
}
class Singleton {
// 使用一个变量来缓存曾经创建的实例
private static Singleton instance;
// 将构造器保用 pirvate 修饰,隐藏该构造器
private Singleton() {
}
// 提供静态方法,用于返回Singleton 实例
// 该方法可以加入自定义的控件,保证只产生一个Singleton
public static Singleton getInstance() {
// 如果instance 为null,表明还不曾创建Singleton 对象
// 如果 intance 不为null ,刚表明已经 创建了Singleton 对象,将不会执行该 方法
if (null == instance) {
instance = new Singleton();
}
return instance;
}
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交