C#通过工厂模式,我把一大堆if干掉了
生活随笔
收集整理的這篇文章主要介紹了
C#通过工厂模式,我把一大堆if干掉了
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
概述
之前做微信項目的時候,會涉及到一個回調,大家都知道回調事件是很多類型的,一般是根據不同的類型在進行不同的邏輯處理。
這樣就會延伸出一個問題,就是入口處會有一大堆if判斷。這樣本身是沒什么問題的,只是看起來比較別扭,那么怎么把if干掉了?。這時候工廠模式派上用場了。下面我們來看下具體如何實現。
代碼實現
1、定義虛方法Notify
2、定義Attribute屬性,并且指定一個參數ServiceName
[System.Serializable][System.AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = false)][System.Runtime.InteropServices.ComVisible(true)]public class InterfaceAttribute : Attribute{private string _ServiceName; public InterfaceAttribute(){}public string ServiceName{get { return _ServiceName; }set { _ServiceName = value; }}}3、實現一個工廠NotifyFactory,通過反射把包含Attribute的找出來
#region Factorypublic class NotifyFactory{public Notify CreateNotify(string _name){Dictionary<string, string> dic = new Dictionary<string, string>();string strNamespace = Assembly.GetExecutingAssembly().GetName().Name;// LogHelper.WriteInfo("命名空間:" + strNamespace);var classes = Assembly.Load(strNamespace).GetTypes();foreach (var item in classes){Object[] obs = item.GetCustomAttributes(typeof(InterfaceAttribute), false);foreach (InterfaceAttribute record in obs){dic.Add(record.ServiceName, item.Name);// LogHelper.WriteInfo("接口名稱:" + record.ServiceName + "-類名:" + item.Name);}}Assembly myAssembly = Assembly.GetExecutingAssembly();Notify Notify = (Notify)myAssembly.CreateInstance(strNamespace + "." + dic[_name]);return Notify;}}#endregion4、前端通過傳入ServiceName,實現不同的業務邏輯
5、其中一個具體的方法重載NotifyHandle,并且定義 ? [Interface(ServiceName = "DIRECT_RECHARGE")]
[Export]/// <summary>/// 代扣交易 InterfaceAttribute 接口名稱 類名自定義 確保命名空間在FuYin.Wallet.Notify 下/// </summary>[Interface(ServiceName = "DIRECT_RECHARGE")]public class DirectRecharge : Notify{public override Result NotifyHandle(NotifyResult r, dynamic respData){// return base.NotifyHandle(Result, respData);//r.ServiceName 異步通知接口方法// r.ResponseType //回調類型LogHelper.WriteInfo("公共數據:" + r.Serialize());DirectRechargeNotifyResult model = JsonConvert.DeserializeObject<DirectRechargeNotifyResult>(respData);LogHelper.WriteInfo("業務處理數據:" + model.Serialize());using (var context = new MefContext()){var svc = context.GetService<IDeTransactionService>();return svc.DirectRechargeNotify(model);}}}這樣就可以把一大堆if去掉了,代碼看起來也簡潔多了。
總結
以上是生活随笔為你收集整理的C#通过工厂模式,我把一大堆if干掉了的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何在 C#9 中使用顶级程序 (top
- 下一篇: .NET6 中的 PriorityQue