gpt4 book ai didi

c# - 如何将 Switch 重构为 Dictionary/Factory

转载 作者:太空狗 更新时间:2023-10-30 00:42:43 26 4
gpt4 key购买 nike

我正在尝试运行从文本文件中读取并逐行解析以动态调用一系列方法的“食谱”。我想我需要在进行大量谷歌搜索后实现一个工厂,但我缺少一些关键细节。这是我最接近的例子:

http://simpleprogrammer.com/2010/08/17/pulling-out-the-switch-its-time-for-a-whooping/

下面的代码是现在的一个片段。

    internal static void Run(int Thread_ID, List<StringBuilder> InstructionSet, List<double>[] Waveforms)
{
//Init
List<double>[] Register = new List<double>[10];
for (int i = 0; i < Waveforms.Length; i++) { Register[i] = new List<double>(Waveforms[i]); }
for (int i = 0; i < Register.Length; i++) { if (Register[i] == null) { Register[i] = new List<double>(); } }

//Run Recipe Steps
foreach (var item in InstructionSet)
{
Step Op = Step.Parse(item.ToString());
switch (Op.TaskName)
{
case "SimpleMovingAverage":
Register[Convert.ToInt32(Op.Args[0])] = Signal_Filters.SimpleMovingAverage(Register[Convert.ToInt32(Op.Args[1])], Convert.ToInt32(Op.Args[2]));
break;

case "RollingSteppedStdDeviation":
Register[Convert.ToInt32(Op.Args[0])] = Signal_Filters.RollingSteppedStdDeviation(Register[Convert.ToInt32(Op.Args[1])], Convert.ToInt32(Op.Args[2]), Convert.ToInt32(Op.Args[3]));
break;

//... etc. many, many methods to be called.
}
}
}

...下面是我有疑问的示例部分:

public static class MoveFactory
{
private static Dictionary<string, Func<IMove>> moveMap = new Dictionary<string, Func<IMove>>()
{
{"Up", () => { return new UpMove(); }},
{"Down", () => { return new DownMove(); }},
{"Left", () => { return new LeftMove(); }}
// ...
};

public static IMove CreateMoveFromName(string name)
{
return moveMap[name]();
}
}
  1. 我可以自动生成词典列表吗?因此,每当我添加一个实现我的工厂接口(interface)(我的 IMove 的等价物)的新类时,我都不必更新我的字典或我的代码的几乎任何其他部分。也许这可以强制作为界面的一部分?

  2. 在上面的示例代码中,我没有看到它传入和传出参数。查看我的代码,我有需要逐步变异的数据...我将如何使用工厂来做到这一点。

  3. 工厂需要线程安全,因为我想将不同的初始数据传递给多个工作人员,每个工作人员都运行自己的配方。

最佳答案

让我们一次解决这些问题。

动态构建字典

使用 Reflection 的组合实际上很容易做到这一点和 Custom Attributes .

属性的创建非常简单,所以我会把它留给您查找,但我们假设您有一个名为 MoveNameAttribute 的属性,它可以在类级别应用。然后,您可以像这样装饰实现 IMove 的类:

[MoveName("Up")]
class UpMove: IMove{}

[MoveName("Down")]
class DownMove: IMove{}

现在您可以使用反射和一点点 LINQ将这些类类型提取到字典中,并使用自定义属性中指定的键按需创建这些类型的新实例。

虽然整个 Factory 本身在代码行方面非常短,但如果您以前从未用过 Reflection,它可能会让人望而生畏。我对每一行都做了注释,以解释发生了什么。

internal static class MoveFactory
{
private static readonly IDictionary<String, Type> _moveTypes;

static MoveFactory()
{
_moveTypes = LoadAllMoveTypes();
}

private static IDictionary<string, Type> LoadAllMoveTypes()
{
var asm =
//Get all types in the current assembly
from type in Assembly.GetExecutingAssembly().GetTypes()
//Where the type is a class and implements "IMove"
where type.IsClass && type.GetInterface("IMove") != null
//Only select types that are decorated with our custom attribute
let attr = type.GetCustomAttribute<MoveNameAttribute>()
where attr != null
//Return both the Name and the System.Type
select new
{
name = attr.Name,
type
};

//Convert the results to a Dictionary with the Name as a key
// and the Type as the value
return asm.ToDictionary(move => move.name, move => move.type);
}

internal static IMove CreateMove(String name)
{
Type moveType;

//Check to see if we have an IMove with the specific key
if(_moveTypes.TryGetValue(name, out moveType))
{
//Use reflection to create a new instance of that IMove
return (IMove) Activator.CreateInstance(moveType);
}

throw new ArgumentException(
String.Format("Unable to locate move named: {0}", name));
}
}

现在您有了自己的工厂,您可以像这样简单地创建新实例:

var upMove = MoveFactory.CreateMove("Up");
var downMove = MoveFactory.CreateMove("Down");

由于工厂使用 Static Constructor ,它只会填充此列表一次,并会自动选择您的新类(class)。

传递参数

我不是 100% 确定您的用例是什么,但看起来您不需要将参数传递给工厂,而是传递给 IMove 上的某个方法。但是,您可以传入数量可变的参数。

如果是这种情况,那么您将不得不忍受设计中的一些丑陋之处。您的 IMove 接口(interface)需要一个非常通用的方法:

public interface IMove
{
double Compute(double val1, params int[] args);
}

现在您的个人移动类将不得不勤奋并检查以确保它们获得正确数量的参数。我将把它留给您作为练习,但是根据上面的示例,这应该可以满足您的需求。

线程安全

就目前而言,上面的工厂实现是线程安全的,因为它不依赖于任何共享状态,并且底层字典本质上是不可变的。每次调用 CreateMove 都会返回一个全新的 IMove 实例。

现在您的 IMove 实现是否线程安全取决于您:)

哇!这是一个很长的答案,但希望这会对您有所帮助。

关于c# - 如何将 Switch 重构为 Dictionary/Factory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13983429/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com