最近碰到了一次工做上的考覈,大概的需求作一個消息統一管理,大體包括微信,短信,微博等信息的消息來源統一管理。****** ,當時實際上是那麼一點點思路,不就是設計模式用適配器模式嘛,把不一樣的接口適配起來就好了,只是想的簡單確不知道怎麼敲鍵盤,週末的時間我的認爲有更重要的事就擱淺到了如今。終於在平時看了那麼多的設計模式以後仍是在今天下午動鍵盤敲了一些代碼,敲完以後內心老是以爲到底應該不該該是這樣,殊不知道應該是怎麼的。下面貼一下我的思路,但願有哪位過來的大神指點指點。設計模式
1.適配器抽象類,原本這裏一開始按照網上看的例子,應該是要用接口形式的,可是考慮到不一樣消息發送須要不一樣的實體,就考慮用的抽象類數組
/// <summary> /// 適配抽象類 /// </summary> public abstract class Adapter<T> { /// <summary> /// 發送消息請求 /// </summary> /// <returns></returns> public abstract string Send(T entity); /// <summary> /// 註冊 /// </summary> /// <returns></returns> public abstract string Register(); } }
2.短信接口緩存
/// <summary> /// 發送短信接口 /// </summary> public interface ISmsSend { /// <summary> ///發送短信請求 /// </summary> /// <param name="entity">短信實體</param> /// <returns></returns> string SendSms(KltxSmsEntity entity); /// <summary> ///註冊/更改回調地址 /// </summary> /// <returns></returns> string RegisterSms(); }
3.短信適配器類微信
/// <summary> /// 短信適配類 /// </summary> public class SmsAdapter : Adapter<KltxSmsEntity> { private readonly ISmsSend _iSmsSend; public SmsAdapter(ISmsSend iSmsSend) { _iSmsSend = iSmsSend; } /// <summary> /// 發送短信請求 /// </summary> /// <returns></returns> public override string Send(KltxSmsEntity entity) { return _iSmsSend.SendSms(entity); } /// <summary> /// 適配短信註冊接口 /// </summary> /// <returns></returns> public override string Register() { return _iSmsSend.RegisterSms(); } }
4.短信接口實現類,這裏的代碼引用了其餘系統的一個實例。dom
/// <summary> /// 短信發送類 /// </summary> public class KltxSmsSend: ISmsSend { /// <summary> /// 註冊/更改回調地址 /// </summary> /// <returns></returns> public string RegisterSms() { var registerClient = new KLTX.SMS.SmsRegisterService.RegisterClient(); var rand = registerClient.getRandom(); var url = ConfigurationManager.AppSettings["GfSmsUrl"]; var ucName= ConfigurationManager.AppSettings["ucName"]; var connId = registerClient.setCallBackAddrV2(ucName, CryptographyHelper.GetMd5Hash(rand + KltxAccount.UcPw + KltxAccount.UcPw), rand, url, "3.0"); return connId; } /// <summary> /// 發送短信請求 /// </summary> /// <param name="entity">短信實體</param> /// <returns></returns> public string SendSms(KltxSmsEntity entity) { var registerClient = new KLTX.SMS.SmsRegisterService.RegisterClient(); string rand = registerClient.getRandom(); var sentClient = new KLTX.SMS.SmsSendService.SendSMSClient(); byte[] bytes = Encoding.Default.GetBytes(entity.Content); string contentBase64 = Convert.ToBase64String(bytes); entity.ConnId=ConfigurationManager.AppSettings["ucConnId"]; string result = sentClient.sendSMSV3(KltxAccount.UcName, CryptographyHelper.GetMd5Hash(rand + KltxAccount.UcPw + KltxAccount.UcPw), rand, entity.CalleeArray, entity.IsReturn, contentBase64, entity.MsgId, entity.ConnId, entity.Charset,entity.SignCont); return result; } }
5.加密解密幫助類ide
/// <summary> /// 加密 /// </summary> public class CryptographyHelper { private const string KeyStr = "Topevery"; private static DESCryptoServiceProvider key = null; static CryptographyHelper() { key = new DESCryptoServiceProvider(); key.Key = Encoding.UTF8.GetBytes(KeyStr); key.IV = Encoding.UTF8.GetBytes(KeyStr); } /// <summary> /// 加密 /// </summary> /// <param name="plainText"></param> /// <returns></returns> public static string Encrypt(string plainText) { try { // Create a memory stream. MemoryStream ms = new MemoryStream(); // Create a CryptoStream using the memory stream and the // CSP DES key. CryptoStream encStream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write); // Create a StreamWriter to write a string // to the stream. StreamWriter sw = new StreamWriter(encStream); // Write the plaintext to the stream. sw.WriteLine(plainText); // Close the StreamWriter and CryptoStream. sw.Close(); encStream.Close(); // Get an array of bytes that represents // the memory stream. byte[] buffer = ms.ToArray(); // Close the memory stream. ms.Close(); // Return the encrypted byte array. return Convert.ToBase64String(buffer); } catch (Exception) { return string.Empty; } } /// <summary> /// 解密 /// </summary> /// <param name="value"></param> /// <returns></returns> public static string Decrypt(string value) { try { // Create a memory stream to the passed buffer. byte[] cypherText = Convert.FromBase64String(value); MemoryStream ms = new MemoryStream(cypherText); // Create a CryptoStream using the memory stream and the // CSP DES key. CryptoStream encStream = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read); // Create a StreamReader for reading the stream. StreamReader sr = new StreamReader(encStream); // Read the stream as a string. string val = sr.ReadLine(); // Close the streams. sr.Close(); encStream.Close(); ms.Close(); return val; } catch (Exception) { return string.Empty; } } /// <summary> /// 將字節數組轉換成字符串 /// </summary> /// <param name="bytes"></param> /// <returns></returns> private string BytesToString(Byte[] bytes) { char[] chars = new char[bytes.Length]; for (int i = 0; i < bytes.Length; i++) { chars[i] = (char)bytes[i]; } string result = new string(chars); return result; } /// <summary> /// 將字符串轉換成字節數組 /// </summary> /// <param name="value"></param> /// <returns></returns> private Byte[] StringToBytes(string value) { byte[] bValue = new byte[value.Length]; for (int i = 0; i < value.Length; i++) { bValue[i] = (byte)value[i]; } return bValue; } public static string GetMd5Hash(string value) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] hashByte = md5.ComputeHash(Encoding.Default.GetBytes(value)); StringBuilder sb = new StringBuilder(); foreach (byte b in hashByte) { sb.Append(b.ToString("x").PadLeft(2, '0')); } return sb.ToString(); } public static bool CompareHashVale(string orginValue, string hashValue) { return String.Compare(GetMd5Hash(orginValue), hashValue, StringComparison.OrdinalIgnoreCase) == 0; } }
6.短信實體類ui
/// <summary> /// 短息實體類 /// </summary> public class KltxSmsEntity { /// <summary> /// 發送短信號碼 /// </summary> public string Callee { set; get; } private List<string> _calleeList = new List<string>(); /// <summary> /// /// </summary> public string[] CalleeArray { get { if (string.IsNullOrEmpty(Callee)) return null; foreach (var cal in Callee.Split(';')) { _calleeList.Add(cal); } return _calleeList.ToArray(); } } /// <summary> /// 短息內容 /// </summary> public string Content { set; get; } /// <summary> /// 終端Id /// </summary> public int MsgId { set; get; } /// <summary> /// 連接Id /// </summary> public string ConnId { set; get; } = ConfigurationManager.AppSettings["ucConnId"]; /// <summary> /// 是否須要回執 /// </summary> public string IsReturn { set; get; } = "0"; /// <summary> /// 短消息內容編碼方式(0:ASCII、 8:Unicode、 15:GBK) /// </summary> public int Charset { get; set; } = 0; /// <summary> /// 短信簽名內容 /// </summary> public string SignCont { get; set; } }
7.方法調用編碼
ISmsSend iSmsSend = new KltxSmsSend();
SmsAdapter smsAdapter = new SmsAdapter(iSmsSend);
KltxSmsEntity entity = new KltxSmsEntity
{
Content = "123",
Callee = "183xxxxxxxx",
MsgId = 3766,
SignCont = "123"
};
smsAdapter.Send(entity);加密
微信的代碼就不上了,大概就是這樣的思路,若是第一步沒有錯的話,接下來一個作的是消息發送記錄本地存儲,消息記錄自動巡查匹配對應的消息類型進行發送接收,以及後續消息緩存,數據分離,由於這仍是理論過程當中,就能夠多想一些。url
其實寫到如今都有一點沒有明白,爲何必定用適配器模式,節省的資源是在什麼地方,這樣寫的好處是在什麼地方,易於擴展仍是便於維護?
但願能有哪位前輩可以指點一下,很是感謝了!