pagehelper 分页插件 Cache缓存创建 工厂模式分析笔记
工厂模式在组件中的运用(pagehelper分页插件)
定义一个Cache接口作为缓存品类的公共接口,定义了get 和 put方法
public interface Cache<K, V> {
V get(K key);
void put(K key, V value);
}
GuavaCache 和 SimpleCache类继承Cache接口通过自定义两参构造方法初始化(配置文件信息,配置前缀信息),并实现了接口中的get 和 put方法
GuavaCache 是谷歌的 com.google.common.cache.CacheBuilder 缓存
public class GuavaCache<K, V> implements Cache<K, V> {
private final com.google.common.cache.Cache<K, V> CACHE;
public GuavaCache(Properties properties, String prefix) {
CacheBuilder cacheBuilder = CacheBuilder.newBuilder();
String maximumSize = properties.getProperty(prefix + ".maximumSize");
...
CACHE = cacheBuilder.build();
}
@Override
public V get(K key) {
return CACHE.getIfPresent(key);
}
@Override
public void put(K key, V value) {
CACHE.put(key, value);
}
}
SimpleCache 是mybatis的 org.apache.ibatis.mapping.CacheBuilder 缓存
public class SimpleCache<K, V> implements Cache<K, V> {
private final org.apache.ibatis.cache.Cache CACHE;
public SimpleCache(Properties properties, String prefix) {
CacheBuilder cacheBuilder = new CacheBuilder("SQL_CACHE");
String typeClass = properties.getProperty(prefix + ".typeClass");
...
CACHE = cacheBuilder.build();
}
@Override
public V get(K key) {
Object value = CACHE.getObject(key);
if (value != null) {
return (V) value;
}
return null;
}
@Override
public void put(K key, V value) {
CACHE.putObject(key, value);
}
}
抽象类 CacheFactory 作为工厂创建缓存 createCache 为创建方法 返还缓存对象
工厂方法解析
public abstract class CacheFactory {
public static <K, V> Cache<K, V> createCache(String sqlCacheClass, String prefix, Properties properties) {
// 是否指定创建缓存类型
if (StringUtil.isEmpty(sqlCacheClass)) {
// 未指定先判断是否存在google的缓存如果存在则创建GuavaCache缓存
try {
Class.forName("com.google.common.cache.Cache");
return new GuavaCache<K, V>(properties, prefix);
} catch (Throwable t) {
// 如果不存在则google的缓存则创建mybatis缓存
return new SimpleCache<K, V>(properties, prefix);
}
} else {
// 指定了创建类型则反射找到类 初始化传入配置文件创建
try {
Class<? extends Cache> clazz = (Class<? extends Cache>) Class.forName(sqlCacheClass);
try {
Constructor<? extends Cache> constructor = clazz.getConstructor(Properties.class, String.class);
return constructor.newInstance(properties, prefix);
} catch (Exception e) {
Cache cache = clazz.newInstance();
if (cache instanceof PageProperties) {
((PageProperties) cache).setProperties(properties);
}
return cache;
}
} catch (Throwable t) {
throw new PageException("Created Sql Cache [" + sqlCacheClass + "] Error", t);
}
}
}
}