求助:Singleton和Factory

03-05-26 zingers

public abstract class ForumFactory {

private static Object initLock = new Object();

private static String className = "com.jivesoftware.forum.database.DbForumFactory";

private static ForumFactory factory = null;

public static ForumFactory getInstance(Authorization authorization) {

//If no valid authorization passed in, return null.

if (authorization == null) {

return null;

}

//以下使用了Singleton 单态模式

if (factory == null) {

synchronized(initLock) {

if (factory == null) {

......

try {

//动态转载类

Class c = Class.forName(className);

factory = (ForumFactory)c.newInstance();

}

catch (Exception e) {

return null;

}

}

}

}

//Now, 返回 proxy.用来限制授权对forum的访问

return new ForumFactoryProxy(authorization, factory,

factory.getPermissions(authorization));

}

//真正创建forum的方法由继承forumfactory的子类去完成.

public abstract Forum createForum(String name, String description)

throws UnauthorizedException, ForumAlreadyExistsException;

....

}

这段代码的意义是只初始化ForumFactory factory 一次,由一个线程实现。

我觉得static Object initLock是类ForumFactory的静态成员,它被锁定

怎么能代表ForumFactory被锁定呢?

jxb8901
2003-05-26 11:26

因为initLock是静态的, 所以在一个JVM中只会存在一个实例, 也就表明任一时刻只能有一个线程拥有该对象的内存锁.