Glide的StateVerifier类 —— 模板模式(Template Pattern) - Bert-King/glide GitHub Wiki
模板模式(Template Pattern)
背景:程序员常常会遇到这种情况:设计一个系统时知道了算法所需的关键步骤,而且确定了这些步骤的执行顺序,但某些步骤的具体实现还未知,或者说某些步骤的实现与具体的环境相关。
现实场景:例如,去银行办理业务一般要经过以下4个流程:取号、排队、办理具体业务、对银行工作人员进行评分等,其中取号、排队和对银行工作人员进行评分的业务对每个客户是一样的,可以在父类中实现,但是办理具体业务却因人而异,它可能是存款、取款或者转账等,可以延迟到子类中实现。
/**
* 抽象(模板)类 StateVerifier 定义了两个抽象方法
* 1. throwIfRecycled()
* 2. setRecycled()
*/
public abstract class StateVerifier {
// 省略无关代码...
/**
* Throws an exception if we believe our object is recycled and inactive (i.e. is currently in an
* object pool).
*/
public abstract void throwIfRecycled();
/** Sets whether or not our object is recycled. */
abstract void setRecycled(boolean isRecycled);
// 具体的实现类:DefaultStateVerifier
private static class DefaultStateVerifier extends StateVerifier {
private volatile boolean isReleased;
@Synthetic
DefaultStateVerifier() {}
@Override
public void throwIfRecycled() {
if (isReleased) {
throw new IllegalStateException("Already released");
}
}
@Override
public void setRecycled(boolean isRecycled) {
this.isReleased = isRecycled;
}
}
// 具体的实现类:DebugStateVerifier
private static class DebugStateVerifier extends StateVerifier {
// Keeps track of the stack trace where our state was set to recycled.
private volatile RuntimeException recycledAtStackTraceException;
@Synthetic
DebugStateVerifier() {}
@Override
public void throwIfRecycled() {
if (recycledAtStackTraceException != null) {
throw new IllegalStateException("Already released", recycledAtStackTraceException);
}
}
@Override
void setRecycled(boolean isRecycled) {
if (isRecycled) {
recycledAtStackTraceException = new RuntimeException("Released");
} else {
recycledAtStackTraceException = null;
}
}
}
}