gpt4 book ai didi

c# - 如何在运行时实现多种策略的使用

转载 作者:太空狗 更新时间:2023-10-29 20:21:59 24 4
gpt4 key购买 nike

我需要处理从服务返回的记录列表。
然而,记录的处理算法完全根据记录上的某个字段而改变。
为了实现这一点,我定义了一个只有一个方法的 IProcessor 接口(interface):

public interface IProcessor
{
ICollection<OutputEntity> Process(ICollection<InputEntity>> entities);
}

对于不同类型的处理,我有两个具体的 IProcessor 实现。
问题是我需要同时使用 IProcessor 的所有实现.. 那么我如何将 IProcessor 注入(inject)我的 Engine 类来驱动整个事情:

public class Engine
{
public void ProcessRecords(IService service)
{
var records = service.GetRecords();
var type1Records = records.Where(x => x.SomeField== "Type1").ToList();
var type2Records = records.Where(x => x.SomeField== "Type2").ToList();

IProcessor processor1 = new Type1Processor();
processor.Process(type1Records);

IProcessor processor2 = new Type2Processor();
processor.Process(type2Records);
}
}

这就是我目前正在做的..而且它看起来不太干净。
关于如何改进此设计的任何想法......也许使用 IoC?

最佳答案

更改您的IProcessor 接口(interface),并添加一个新函数:

public interface IProcessor
{
ICollection<OutputEntity> Process(InputEntity> entity);
bool CanProcess (InputEntity entity);
}

那么您的代码不需要知道任何关于实现的信息:

foreach (var entity in entities) {
var processor = allOfMyProcessors.First(p=>p.CanProcess(entity));

processor.Process(entity);
}

你的处理器会施展魔法:

public class Processor1 : IProcessor {
public bool CanProcess(InputEntity entity) {
return entity.Field == "field1";
}
}

这种方法的好处是您可以从程序集等加载新的处理器,而您的主要代码实现不必知道那里的任何单个实现。

关于c# - 如何在运行时实现多种策略的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6029254/

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