定义一个操作中的算法的骨架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
模板方法的核心思想是:父类定义骨架,子类实现某些细节。
比如有一个缓存的获取方式,有两种实现方式,本地缓存,Redis缓存,如果我们从缓存里面没有获取到,那么需要去数据库里面读取,再放进缓存里面。
UML类图如下:
定义方法类:
public abstract class AbstractCache {
public final Object getCache(String key) {
Object value = lookUpCacheByKey(key);
if (value == null) {
value = readFromDb(key);
putIntoCache(key,value);
}
return value;
}
protected abstract void putIntoCache(String key, Object value);
protected abstract Object lookUpCacheByKey(String key);
public final Object readFromDb(String key) {
// 省略
return null;
}
}
定义子类
public class LocalCache extends AbstractCache{
private Map<String,Object> map = new ConcurrentHashMap<>();
@Override
protected void putIntoCache(String key, Object value) {
map.put(key, value);
}
@Override
protected Object lookUpCacheByKey(String key) {
return map.get(key);
}
}
public class RedisCache extends AbstractCache {
private RedisClient client = RedisClient.create("redis://localhost:6379");
@Override
protected void putIntoCache(String key, Object value) {
try (StatefulRedisConnection<String, String> connection = client
.connect()) {
RedisCommands<String, String> commands = connection.sync();
commands.set(key, value);
}
}
@Override
protected Object lookUpCacheByKey(String key) {
try (StatefulRedisConnection<String, String> connection = client
.connect()) {
RedisCommands<String, String> commands = connection.sync();
return commands.get(key);
}
}
}