public class ContextBase extends HashMap implements Context {
public Object put(Object key, Object value) {
// Case 1 -- no local properties
if (descriptors == null) {
return (super.put(key, value));
}
// Case 2 -- this is a local property
if (key != null) {
PropertyDescriptor descriptor =
(PropertyDescriptor) descriptors.get(key);
if (descriptor != null) {
Object previous = null;
if (descriptor.getReadMethod() != null) {
previous = readProperty(descriptor);
}
writeProperty(descriptor, value);
return (previous);
}
}
// Case 3 -- store or replace value in our underlying map
return (super.put(key, value));
}
public Object get(Object key) {
// Case 1 -- no local properties
if (descriptors == null) {
return (super.get(key));
}
// Case 2 -- this is a local property
if (key != null) {
PropertyDescriptor descriptor =
(PropertyDescriptor) descriptors.get(key);
if (descriptor != null) {
if (descriptor.getReadMethod() != null) {
return (readProperty(descriptor));
} else {
return (null);
}
}
}
// Case 3 -- retrieve value from our underlying Map
return (super.get(key));
}
}
return false 会继续执行chain中后续的command,return true就不会了。
3.Chain
chain of command
实现源码
public class ChainBase implements Chain {
public void addCommand(Command command) {
if (command == null) {
throw new IllegalArgumentException();
}
if (frozen) {//execute method will freeze the configuration of the command list
throw new IllegalStateException();
}
Command[] results = new Command[commands.length + 1];
System.arraycopy(commands, 0, results, 0, commands.length);
results[commands.length] = command;
commands = results;
}
public boolean execute(Context context) throws Exception {
// Verify our parameters
if (context == null) {
throw new IllegalArgumentException();
}
// Freeze the configuration of the command list
frozen = true;
// Execute the commands in this list until one returns true
// or throws an exception
boolean saveResult = false;
Exception saveException = null;
int i = 0;
int n = commands.length;
for (i = 0; i < n; i++) {
try {
saveResult = commands.execute(context);
if (saveResult) {//false继续执行chain下面的command,true 就直接返回不再执行了其他command
break;
}
} catch (Exception e) {
saveException = e;
break;
}
}
// Call postprocess methods on Filters in reverse order
if (i >= n) { // Fell off the end of the chain
i--;
}
boolean handled = false;
boolean result = false;
for (int j = i; j >= 0; j--) {
if (commands[j] instanceof Filter) {//filter定义了postprocess方法,用于自定义处理结束执行资源释放的操作
try {
result =
((Filter) commands[j]).postprocess(context,
saveException);
if (result) {
handled = true;
}
} catch (Exception e) {
// Silently ignore
}
}
}
// Return the exception or result state from the last execute()
if ((saveException != null) && !handled) {
throw saveException;
} else {
return (saveResult);
}
}
}
3.filter:是一种特殊的command,加入了postprocess 方法。在chain return之前会去执行postprocess。可以在该方法中释放资源。
4.catalog:command或chain的集合。通过配置文件类加载chain of command 或者command。通过catalog.getCommand(commandName)获取Command。