c# – 如何在运行时实现多个策略的使用
发布时间:2020-12-15 08:02:21 所属栏目:百科 来源:网络整理
导读:我需要处理从服务返回的记录列表. 然而,记录的处理算法完全基于记录上的某个字段而改变. 为了实现这一点,我定义了一个只有一个方法的IProcessor接口: public interface IProcessor{ ICollectionOutputEntity Process(ICollectionInputEntity entities);} 我
我需要处理从服务返回的记录列表.
然而,记录的处理算法完全基于记录上的某个字段而改变. 为了实现这一点,我定义了一个只有一个方法的IProcessor接口: public interface IProcessor { ICollection<OutputEntity> Process(ICollection<InputEntity>> entities); } 我有两种具体的IProcessor实现,用于不同类型的处理. 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); } } 这就是我目前正在做的事情……它看起来并不好看. 解决方法
您可以将SomeField规范放在IProcessor实现中(您必须向IProcessor接口添加一个额外的字段),并根据您当前使用的处理器查找相应的记录.
一些代码清除它: public interface IProcessor { ICollection<OutputEntity> Process(ICollection<InputEntity>> entities); string SomeField{get;set;} } public class Engine { public Engine(IEnumerable<IProcessor> processors) { //asign the processors to local variable } public void ProcessRecords(IService service) { // getRecords code etc. foreach(var processor in processors) { processor.Process(typeRecords.Where(typeRecord => typeRecord.SomeField == processor.SomeField)); } } } 或者,您可以在ProcessRecords方法中提供IProcessors,或者在Engine类中将它们设置为Properties(尽管我更喜欢构造函数注入). 编辑 您可能还想在其他答案中查看CanProcess方法.虽然原理是相同的,但如果您需要更改标准以决定处理器是否应该处理类型,它会提供更加可扩展/可靠的解决方案. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- 何时以及如何在Swift中使用@noreturn属性?
- vue-cli 3.x 配置Axios(proxyTable)跨域代理方法
- IOS设备方向卡在纵向模式下,没有横向
- ruby-on-rails – 你如何从nitrous.io推送到GIT
- ajax – 反CSRF令牌和Javascript
- xml – UPS包跟踪API – 如何不泄露密码?
- c# – System.Speech.Recognition是否使用“语音
- ajax – angular2使用HTTP发布XML类型请求数据
- Array与ArrayCollection的区别
- c# – 将xaml代码ItemsSource =“{Binding}”设置
热点阅读