我现在正在考虑的想法是拥有一个多层次的分析对象“层”系统,该系统对公共(public)对象执行一定的计算,然后根据其结果创建一组新的分析对象。然后,新创建的分析对象将轮流运行并可选择创建更多分析对象,依此类推。要点是子分析对象将始终在创建它们的对象之后执行,这是相对重要的。整个设备将由单个线程调用,因此我目前不关心线程安全。只要满足一定的基本条件,我不认为这是一个不稳定的设计,但我仍然对此感到有点不安。
这是一些严重的代码味道还是我应该继续以这种方式实现它?有更好的办法吗?
这是一个示例实现:
namespace WidgetTier
{
public class Widget
{
private string _name;
public string Name
{
get { return _name; }
}
private TierManager _tm;
private static readonly Random random = new Random();
static Widget()
{
}
public Widget(string name, TierManager tm)
{
_name = name;
_tm = tm;
}
public void DoMyThing()
{
if (random.Next(1000) > 1)
{
_tm.Add();
}
}
}
//NOT thread-safe!
public class TierManager
{
private Dictionary<int, List<Widget>> _tiers;
private int _tierCount = 0;
private int _currentTier = -1;
private int _childCount = 0;
public TierManager()
{
_tiers = new Dictionary<int, List<Widget>>();
}
public void Add()
{
if (_currentTier + 1 >= _tierCount)
{
_tierCount++;
_tiers.Add(_currentTier + 1, new List<Widget>());
}
_tiers[_currentTier + 1].Add(new Widget(string.Format("({0})", _childCount), this));
_childCount++;
}
//Dangerous?
public void Sweep()
{
_currentTier = 0;
while (_currentTier < _tierCount) //_tierCount will start at 1 but keep increasing because child objects will keep adding more tiers.
{
foreach (Widget w in _tiers[_currentTier])
{
w.DoMyThing();
}
_currentTier++;
}
}
public void PrintAll()
{
for (int t = 0; t < _tierCount; t++)
{
Console.Write("Tier #{0}: ", t);
foreach (Widget w in _tiers[t])
{
Console.Write(w.Name + " ");
}
Console.WriteLine();
}
}
}
class Program
{
static void Main(string[] args)
{
TierManager tm = new TierManager();
for (int c = 0; c < 10; c++)
{
tm.Add(); //create base widgets;
}
tm.Sweep();
tm.PrintAll();
Console.ReadLine();
}
}
}
最佳答案
是的,我将以下代码称为气味:
_currentTier = 0;
while (_currentTier < _tierCount) //_tierCount will start at 1 but keep increasing because child objects will keep adding more tiers.
{
foreach (Widget w in _tiers[_currentTier])
{
w.DoMyThing();
}
_currentTier++;
}
当集合发生变化时,您正在对其进行迭代。我的意思是第一次迭代,而不是第二次。显然,您正在考虑这种变化(因此是 < _tierCount
而不是标准 foreach
),但在我看来,它仍然是一种气味。
我会把它放入生产代码中吗?可能吧。取决于场景。但我会觉得很肮脏。
还有:您的_tiers
成员也可以轻松成为 List<List<Widget>>
。
关于c# - 带有分析小部件的分层设计 - 这段代码有味道吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2541375/