根据上下文更改代码行为
我有一个可以从 GUI 调用或形成非图形环境(批处理模式)的类
“告诉”代码中与 GUI 相关的部分不要执行的最方便的最佳实践方法是什么当以批处理模式执行时。
我想到类似的东西
public MyMethod()
{
[@TAG: DOTHIS_ONLY_IF_GUIMODE]
ShowPanels();
....
}
,并且 GUI_MODE_ACTIVATED 将在运行时在某个地方设置为 true 或 false,具体取决于调用程序的位置
我想避免丑陋的跟踪 if/else 东西分散在我的代码中。
我的小拇指告诉我 AOP 是可行的方法(但如果我设法找到一个更简单的替代方案,我会选择它)
那么,最简单、最直接的方法是什么?
更新: 正如大多数贡献者指出的那样,将 GUI 代码与业务代码分开是一条经验法则,但我仍然有兴趣知道如何做到这一点,即使不涉及 GUI(即两个不同的例如,适用于两种不同环境的 BATCH 模式)
I have a class that can be called either from a GUI or form a Non-Graphical Environment (Batch mode)
What is the most convenient an best practice way to "tell" the GUI-related parts of the code NOT to execute when executed in batch mode.
I think of something like
public MyMethod()
{
[@TAG: DOTHIS_ONLY_IF_GUIMODE]
ShowPanels();
....
}
And the GUI_MODE_ACTIVATED would be set to true or false on runtime somewhere, depending on where the program is called from
I want to avoid the ugly tracing if/else stuff scattered all over my code.
My little thumb tells me AOP is the way to go (but if I manage to find a simpler alternative I'll go for it)
So, what is the SIMPLEST and most straightforward way to do this ?
Update:
As most contributors pointed out, separating GUI Code from Business code is a rule of thumb, But I am still interested in knowing ways to do this even if NO GUI is involved (ie, two different BATCH modes for two different environments, for example)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为最好的选择是将特定于 GUI 的代码从类中取出,并实现在类处理的关键时刻触发的事件。当由 GUI 调用时,GUI 代码会订阅这些事件并“做正确的事情”。批处理代码忽略这些事件,一切都很好。
I think your best bet is to take the GUI-specific code out of the class and implement events triggered at key times in the class's processing. When called by the GUI, the GUI code subscribes to those events and 'does the right thing.' The batch-code ignores the events and all is well.
这就是为什么将业务逻辑问题与 UI 问题分开的原因。
将业务逻辑问题与 UI 问题分开。
This is why you separate business logic concerns from UI concerns.
Separate business logic concerns from UI concerns.
最简单、最直接的方法是使用
if
语句。一种不太直接但更结构化的方法是使 ShowPanels 方法抽象,然后派生两个类:一个用于 GUI 模式,一个用于批处理模式。
The simplest and most straightforward way is to use an
if
statement.A less straightforward, but more structured, way would be to make the
ShowPanels
method abstract, then derive two classes: one for GUI mode and one for batch mode.使用动态装饰器向对象添加方面
。
您的类应该只关注业务逻辑而不是表示(GUI 或 Batch 等)。在运行时,您可以根据需要将表示(GUI 或非 GUI)代码附加到类的对象。
类定义中不需要有丑陋的属性代码。
Add Aspects to Object Using Dynamic Decorator
.
Your classs should concern only business logic not presentation (GUI or Batch, etc.). At runtime, you can attach presentation (GUI or non-GUI) code to objects of the class as needed.
No need to have the ugly attribute code in your class definition.