首页 > 代码库 > 反射动态创建不同的Processor
反射动态创建不同的Processor
1. 定义抽象方法
public abstract class BaseProcesser
{
public abstract void GetCustomerReportCardDetailInfo(CustomerReportCardRequest request, ReportCardResult response);
}
2. 所有Processor都继承自BaseProcessor
public class GiftProcesser : BaseProcesser
{
public override void GetCustomerReportCardDetailInfo(CustomerReportCardRequest request, ReportCardResult response)
{
response.GiftInfo = GiftAccessor.GetGiftInfo(request);
}
}
3.将Processor的名称配置起来,通过反射动态加载去执行
4.具体示例如下:
public static CustomerReportCardResponse GetCustomerReportCardInfo(CustomerReportCardRequest request, string view, string[] expand) { ReportCardResult result = new ReportCardResult(); List<string> currencyCodes = new List<string>(); if (view == "DETAIL") { if (!CheckCurrencyCode(request, ref currencyCodes)) { return null; } IEnumerable<string> processKeys = AllProcessers.Where(n => expand.Contains(n.Key)).Select(n => n.Key); foreach (var key in processKeys) { var processer = AllProcessers[key]; processer.GetCustomerReportCardDetailInfo(request, result); } } return SetCustomerReportCardResponse(result, request, currencyCodes); } private static Dictionary<string, BaseProcesser> allProcessers = null; private static Dictionary<string, BaseProcesser> AllProcessers { get { if (allProcessers == null) { allProcessers = new Dictionary<string, BaseProcesser>(); Dictionary<string, string> classNames = GetResource(); foreach (var key in classNames.Keys) { BaseProcesser detail = typeof(BaseProcesser).Assembly.CreateInstance(classNames[key]) as BaseProcesser; if (detail == null) continue; if (!allProcessers.ContainsKey(key)) { allProcessers.Add(key, detail); } } } return allProcessers; } } private static Dictionary<string, string> GetResource() { Dictionary<string, string> result = new Dictionary<string, string>(); PerKeyValue keyValue = http://www.mamicode.com/ConfigContainer.KeyValuesConfig["CustomerReportCardExpand"]; if (keyValue =http://www.mamicode.com/= null) return null;"Class"].Value; foreach (PerKeyValue resource in keyValues) { if (resource == null) continue; result.Add(resource.Name, assemblyBase + "." + resource.Value); } return result; }
反射动态创建不同的Processor
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。