Java登记式单例类的问题?

cjdxhc 2009-07-09 09:33:22
import java.util.HashMap;

public class RegSingleton {
private static HashMap rss = new HashMap();

static {
RegSingleton regSingleton = new RegSingleton();
rss.put(regSingleton.getClass().getName(), regSingleton);
}

//保护的默认构造器
protected RegSingleton() {

}

//静态工厂方法,返还此类惟一的实例
public static RegSingleton getInstance(String name) {
if (name == null)
name = RegSingleton.class.getName();
if (rss.get(name) == null) {
try {
rss.put(name, Class.forName(name).newInstance());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return (RegSingleton) rss.get(name);
}
}

为什么可以直接new出来呢?既然可以new如何保证就一个实例存在呢?

登记式单例类是为了克服饿汉式单例类及懒汉式单例类均不可继承的缺点而设计的。
它的子类RegSingletonChild 需要父类的帮助才能实例化。

public class RegSingletonChild extends RegSingleton {

public RegSingletonChild() {}

/**

* 静态工厂方法

*/

static public RegSingletonChild getInstance(){

return (RegSingletonChild)

RegSingleton.getInstance(

"com.javapatterns.singleton.demos.RegSingletonChild" );

}

/**

* 一个示意性的商业方法

*/

public String about() {

return "Hello, I am RegSingletonChild.";

}

}

上面构造器不是public的吗?不是也可以直接new出来吗??
不是很理解这种情况!望高人指点!
...全文
79 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
cjdxhc 2009-07-10
  • 打赏
  • 举报
回复
rss.put(name, Class.forName(name).newInstance());
为什么要把其他对象也注册到集合中???
liang8305 2009-07-10
  • 打赏
  • 举报
回复
个人意见,讨论讨论

上面的例子,我想不到它的应用场景
就“注册式”这个字面的概念来理解,配上应用场景
程序是否可以是这样:

注册管理者:
import java.util.HashMap;

public class RegManager {
private static HashMap rss = new HashMap();

static {
RegManager regSingleton = new RegManager();
rss.put(regSingleton.getClass().getName(), regSingleton);
}

private RegManager(){}



// 静态工厂方法,返还此类惟一的实例
public static RegManager getInstance(String name) {
if (name == null)
name = RegManager.class.getName();
if (rss.get(name) == null) {
try {
rss.put(name, Class.forName(name).newInstance());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return (RegManager) rss.get(name);
}
}


然后其他需要通过登记管理者才能获得的单例,跟其他普通单例一样,
只是getInstance()方法不再是public而是protected
这样就能限制所有包外的类要获得单例,只能通过管理者获取

也就所谓的“登记”;






cjdxhc 2009-07-10
  • 打赏
  • 举报
回复
希望高手解决啊!

81,114

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧