看看一段工厂模式的代码是否正确?

只有一个叫GameFactroy的类:


public class GameFactroy {

public static Logger logger = Logger.getLogger(GameFactroy.class);

public GameFactroy() { }
/**
* Construct a game instance
* @param _gameClassPath The game class path is stored in game.xml
* @see GameKind
* @return game instanc
* @throws GameFactroyException
*/

public GameInterface getGameInstance(String gameClassPath) throws GameFactroyException{
try{
Class c = Class.forName(gameClassPath);
GameInterface game = (GameInterface)c.newInstance();
logger.info(
"Susccess contruct a game instance,gameClassPath=" + gameClassPath);
return game;
}catch(Exception ex){
logger.error(
"Can not construct a game instance,gameClassPath=" + gameClassPath + ",Error=" + ex);
throw new GameFactroyException(
"Can not construct a game instance");
}
//end try-catch
}
}

没有concrete class

看看客户端调用:

GameInterface game=gameFactroy.getGameInstance(gameClassPath);
gameClassPath是game的一个实例concrete class的类的名称。

有什么不对的地方么?我并没有看出来啊?

public static Logger logger = Logger.getLogger(GameFactroy.class);

这是干什么用的?

加一个Hashtable来存实例


private java.util.Hashtable hashtable = new Hashtable();

GameInterface game = (GameInterface) hashtable.get(gameClassPath);
if(game == null) {
try{
Class c = Class.forName(gameClassPath);
game = (GameInterface)c.newInstance();
logger.info("Susccess contruct a game instance,gameClassPath=" + gameClassPath);
}catch(Exception ex){
logger.error(
"Can not construct a game instance,gameClassPath=" + gameClassPath + ",Error=" + ex);
throw new GameFactroyException(
"Can not construct a game instance");
}
//end try-catch
}
return game;

日志处理

这是一个工厂方法+动态载入。

为什么gameFactroy()不是静态方法?反正只有一个工厂方法
否则使用起来还得实例化,麻烦!
其它没有什么错误啊???

gameClassPath是game的一个实例concrete class的类的名称。

请,说清楚一点!最好举个例子.

我猜 GameInterface 是一个接口,
然后你有一个类实现了这个接口,这个类的名字存放在 gameClassPath 里

是这样吗?

对 不用说,你不是估计出来了?

如果是这样,那你还有什么疑问? ^_^

和楼上的疑问类似:
为什么gameFactroy()不是静态方法?

你试过这种情况没有?
如果构造方法是一个 private 的,
Class.forName().newInstance() 能不能得到实例?

我没试过,等待你的结果

构造函数private
get方法用static

嗯,我测试了一下,发现即使构造方法是 private 的,还是能通过
Class.forName().newInstance() 来获得对象的实例.
我原来认为,如果这是不可能的,那在应用独子模式时,可能就会有点问题.
但是现在看起来,并不是这样.虚拟机从内部能实现 private 方法的调用.

对上面那段代码,我只能理解为,作者并不希望该对象只有一个实例.
特别是在多线程的情况下


也就是说,每个线程都要动态装载一次,不能使用
if (game==null)
再load Class.forName().newInstance()

这样的lazy 方法.

无疑会影响速度,这个类从名字上看就知道处于系统的一个关键位置上。
这样会降低整个系统的速度,是不是可以这样理解?