我的问题是创建一个可以安全使用对象(设置容器或简单容器)的类。我有 10 多种方法,我必须重复相同的操作:保存容器的状态、更改状态、做一些工作、恢复状态、返回结果。示例:
public List<String> childKeys() {
//saving state (repeated many time in other methods)
final String clientGroup = clientSettings.group();
//changing state (repeated many time in other methods)
clientSettings.endAllGroups();
clientSettings.beginGroup(currentGroup);
//doing job (exclusive for each method)
final List<String> childKeys = clientSettings.childKeys();
//restoring state (repeated many time in other methods)
clientSettings.endAllGroups();
clientSettings.beginGroup(clientGroup);
return childKeys;
}
我需要这样做以防止用户更改系统设置,并希望避免多次编写相同的代码。
您是否看到任何重新设计代码的方法,以便可以准备和自动清理方法调用?
最佳答案
如果我理解您的意思,您想确保在一组特定方法之前和/或之后调用特定代码?
你有没有考虑过AOP ?这将是一种很好的方法,可以将相同的代码添加到一堆方法调用中,而不会到处都被父类(super class)/额外调用污染您的代码。
Spring-AOP是它的一个很好的实现,它在底层使用了 AspectJ。看看。
关于java - OOP 设计 - 需要准备每个方法调用并在之后清理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8309795/