如何保证方法按照正确的顺序执行?
我一直在设计一个类,其中正确的方法调用对程序员来说是清楚的,并且在数据、变量由其他方法设置之前执行某些方法不会有危险。所以为了安全起见,我通常使用标志和 If 语句:
class foo {
boolean isInitialised = FALSE;
boolean isSthDone = FALSE;
float importantData;
public void initialise {
...
isInitialised = TRUE;
}
public void doSth1 {
if (isInitialised) {
importantData = 2134234;
} ...
isSthDone = TRUE;
}
public void doSth2 {
if (isInitialised && isSthDone1) {
...
}
}
}
这种设计没有给出任何线索,应该如何使用算法 - 应该首先执行哪个方法,有没有针对这个问题的设计模式?
I have always problem to design a class where proper method invocation would be clear to programmer, and there will be no danger of executing some method before data, variables are set by other method. So I usually use flags and If statements to be safe:
class foo {
boolean isInitialised = FALSE;
boolean isSthDone = FALSE;
float importantData;
public void initialise {
...
isInitialised = TRUE;
}
public void doSth1 {
if (isInitialised) {
importantData = 2134234;
} ...
isSthDone = TRUE;
}
public void doSth2 {
if (isInitialised && isSthDone1) {
...
}
}
}
This kind of design does not give any clue, how the algorithm should be used - which method should be executed first, is there any Design Pattern for this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
考虑一下独立执行这些步骤是否真的有意义。如果该类的使用者确实必须严格按照该顺序执行步骤 1、步骤 2 和步骤 3,那么只需将它们折叠到一个公共方法中并将这些步骤封装在类中即可。
另一方面,如果消费者按照什么顺序执行操作确实有多种选择,那么您就会遇到状态转换问题,并且您需要了解步骤的合法顺序。
Give some thought to whether independent execution of those steps really makes sense at all. If the consumer of that class really has to execute step 1, step 2, and step 3 in exactly that order, then just collapse them into one public method and encapsulate the steps within your class.
If, on the other hand, there really are options in terms of what the consumer does in which order, then you've got a state-transition problem, and you need to understand the legal sequences of steps.
您应该在构造函数中进行所需的初始化 - 初始化正是构造函数的用途。根据您使用的语言,它可能如下所示:
You should be doing needed initialization in the constructor - that initialization is exactly what a constructor is for. Depending on the language you are using, it might look like this:
@D。兰伯特和@David 给出了很好的建议。
如果您想要一种强制调用序列的设计模式,请查看模板方法。这可能不是您想要的,而且我过去很后悔选择该模式,因此请小心使用。无论你喜欢与否,它都会强制执行命令。
@D. Lambert and @David are giving good advice.
If you want a design pattern that enforces a sequence of calls, look at Template Method. That's probably not what you want here, and I have regretted choosing that pattern in the past, so use it with care. It enforces an order whether you like it or not.
您应该考虑在此处使用State。对我来说,你的代码看起来像:
http://sourcemaking.com/design_patterns/state
无论如何,就像之前告诉您的那样,最简单的选择是将这些方法设为私有,并从一个新的公共方法中按良好的顺序调用它们。
You should consider using State here. For me your code looks like:
http://sourcemaking.com/design_patterns/state
Anyway, like you were told before, the easiest option is to make those methods private and call them all in good order from one new public method.