【发布时间】:2018-03-02 01:37:56
【问题描述】:
根据一些文章:
理论说这很容易,但实际上这通常很困难。 没关系。让我们深入了解这件事的核心。
代码如下所示:
public class SomeType
{
// Some properties.
}
public enum SomeTrigger
{
Loaded,
Initial,
Timer,
Final
}
public class SomeBaseObject
{
//
// I am not allowed to change this class. It is not mine.
//
protected Dictionary<string, SomeType> Input;
protected Dictionary<string, SomeType> Output;
// Timer is evaluated every 2 sec.
public virtual void Execute(SomeTrigger trigger, string value)
{
switch (trigger)
{
case SomeTrigger.Loaded:
break;
case SomeTrigger.Initial:
break;
case SomeTrigger.Timer:
break;
case SomeTrigger.Final:
break;
default:
break;
}
}
// The rest of code...
}
还有我想改进的课程:
public class SomeSpecificObject : SomeBaseObject
{
private bool isInitializationCompleted;
private string connection;
public override void Execute(SomeTrigger trigger, string value)
{
switch (trigger)
{
case SomeTrigger.Loaded:
this.OnLoaded();
break;
case SomeTrigger.Initial:
this.OnInitial();
break;
case SomeTrigger.Timer:
this.OnTimer();
break;
case SomeTrigger.Final:
this.OnFinal(value);
break;
default:
break;
}
}
private void OnLoaded()
{
// Read Input and Output collection.
}
private void OnInitial()
{
// Initialization (connect to the server).
// Bla bla bla
this.connection = //Value from the plug-in;
this.isInitializationCompleted = true;
}
private void OnTimer()
{
if (isInitializationCompleted)
{
// Do something
// Connection is using here.
// Calculate values on a Input collection, etc.
}
}
private void OnFinal(string value)
{
if (isInitializationCompleted)
{
// something with "value"
// Connection is using here.
// Clear state.
}
else
{
// Connection is using here.
// Cancel inistialization
}
}
}
我该怎么办?每个字段都在使用但每个触发器。此外,一种情况有点具体(OnFinalMethod 需要参数)。根据以上文章,我尝试重构这段代码,但没有成功。
My attempts to apply some tips:
public interface ITrigger
{
void Execute();
}
public class LoadedTrigger : ITrigger
{
public void Execute()
{
throw new NotImplementedException();
}
}
//
// Exactly the same class for the rest cases.
//
public class TriggerHandler
{
private Dictionary<SomeTrigger, ITrigger> triggerDictionary;
public TriggerHandler()
{
triggerDictionary.Add(SomeTrigger.Loaded, new InitialTrigger());
// and for the rest
}
public void HandleTrigger(SomeTrigger trigger)
{
triggerDictionary[trigger].Execute();
}
}
对象应该如何相互通信?例如。 TimerTrigger 对象需要知道启动是否成功。我应该如何处理特殊情况对象?
有什么想法吗? :)
【问题讨论】:
-
不清楚您要解决什么问题,但一种可能有效的设计模式是Strategy Pattern。查看示例 here 和 here。
-
@NightOwl888 - 我已经简化了这个例子。在实际项目中,switch 语句有 8 种情况,只有一个类处理所有这些行为。这个类真的很大,我认为将一些功能委托给单独的类是个好主意。
-
可能是访问者模式的双重分派,但你需要重构你的代码。
标签: c# design-patterns architecture