在JForum中,net.jforum.cache.CacheEngine接口提供了这些方法:
我觉得,只有第一类方法,不要第二类方法也是可以的。之所以有第二类,可能是出于分类管理的考虑。例如,在SessionFacade类中,作者就定义了如下六类:
public class SessionFacade { private static final String FQN = "sessions"; private static final String FQN_LOGGED = FQN + "/logged"; private static final String FQN_COUNT = FQN + "/count"; private static final String FQN_USER_ID = FQN + "/userId"; private static final String ANONYMOUS_COUNT = "anonymousCount"; private static final String LOGGED_COUNT = "loggedCount"; }
否则的话,看到cache.add(FQN, us.getSessionId(), us);这样的代码,可能会有疑惑:cache.add(us.getSessionId(), us);不就可以了吗?
有三个类实现了CacheEngine接口,如图:
DefaultCacheEngine没有使用第三方缓存框架,只是使用了Map cache = new HashMap()。其余两个实现就不多说了。如果谁想了解Ehcache和JBoss Cache的入门知识,就可以参考这两个类。
还要说的是net.jforum.cache.Cacheable接口,
public interface Cacheable { /** * Sets the cache engine instance. * @param engine The instance of the cache engine */ public void setCacheEngine(CacheEngine engine); }
有11个类实现了该接口,但都类似于
public class SessionFacade implements Cacheable { private static CacheEngine cache; public void setCacheEngine(CacheEngine engine) { cache = engine; } }
好像没有什么意义。为什么要设计一个Cacheable接口?
见
package net.jforum; public class ConfigLoader { public static void startCacheEngine() { try { String cacheImplementation = SystemGlobals.getValue(ConfigKeys.CACHE_IMPLEMENTATION); logger.info("Using cache engine: " + cacheImplementation); cache = (CacheEngine)Class.forName(cacheImplementation).newInstance(); cache.init(); String s = SystemGlobals.getValue(ConfigKeys.CACHEABLE_OBJECTS); if (s == null || s.trim().equals("")) { logger.warn("Cannot find Cacheable objects to associate the cache engine instance."); return; } String[] cacheableObjects = s.split(","); for (int i = 0; i < cacheableObjects.length; i++) { logger.info("Creating an instance of " + cacheableObjects[i]); Object o = Class.forName(cacheableObjects[i].trim()).newInstance(); if (o instanceof Cacheable) { ((Cacheable)o).setCacheEngine(cache); } else { logger.error(cacheableObjects[i] + " is not an instance of net.jforum.cache.Cacheable"); } } } catch (Exception e) { throw new CacheEngineStartupException("Error while starting the cache engine", e); } } }
作者将11个Cacheable实现类都写在配置文件中,并集中设置了setCacheEngine()了。可见,这是Cacheable接口的意义。
注意:这11个Cacheable实现类中,除setCacheEngine(CacheEngine engine)方法外,都是静态方法。否则,这种通过注入的方式初始化CacheEngine cache是不可行的。