编程论坛
注册
登录
编程论坛
→
J2EE论坛
求教J2EE中的单例
罗彬
发布于 2008-11-15 13:57, 983 次点击
我刚学习J2EE,为什么我们编写UserManager的时候,一般都是用单例模式编写,为什么不用多例??像编写要struts中的工action一样。况且单例模式编写,还有线程安全问题的嘛。。求各位高手指教。谢谢了
4 回复
#2
huwangvs
2008-11-15 14:13
看名字,UserManager应该是工厂类似的功能。
既然是工厂,一个还不够吗?一般都是从工厂里面取东西,多线程也无所谓啊。又不会改变什么。
#3
罗彬
2008-11-15 23:36
谢谢。
#4
小乌龟
2008-11-19 16:53
饿汉单例模式
public class EagerSingleton
{
private static final EagerSingleton m_instance = new EagerSingleton();
private EagerSingleton() { }
public static EagerSingleton getInstance()
{
return m_instance;
}
}
#5
小乌龟
2008-11-19 16:54
懒汉单例模式
public class LazySingleton
{
private static LazySingleton
m_instance = null;
private LazySingleton() { }
synchronized public static LazySingleton
getInstance()
{
if (m_instance == null)
{
m_instance = new LazySingleton();
}
return m_instance;
}
}
1