這兩個類別是建造者模式中的「產品」角色,提供實際的資料操作方法:
using System;
using System.Collections.Generic;
using System.Text;
namespace Pattern.Builder
{
///
/// XML 方式操作 Message
///
public class XMLMessage
{
///
/// 獲取 Message
///
/// MessageModel 清單
public List<MessageModel> Get()
{
List<MessageModel> l = new List<MessageModel>();
l.Add(new MessageModel("XML方式獲取Message", DateTime.Now));
return l;
}
///
/// 插入 Message
///
/// Message 實體物件
/// 是否成功
public bool Insert(MessageModel mm)
{
// 程式碼略
return true;
}
}
}
Operation 類別封裝建造完成的指令字串,並透過反射動態載入並執行對應方法:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace Pattern.Builder
{
///
/// 操作(Product)
///
public class Operation
{
private string _type;
private Dictionary<string, string> _dictionary;
///
/// 建構函式
///
/// 產品類型
public Operation(string type)
{
_dictionary = new Dictionary<string, string>();
this._type = type;
}
///
/// 索引器:存取指令字串
///
public string this[string key]
{
get { return _dictionary[key]; }
set { _dictionary[key] = value; }
}
///
/// 獲得執行結果:透過反射動態調用
///
public string GetResult()
{
Assembly assembly = Assembly.Load("Pattern.Builder");
// 執行 Get 方法
MethodInfo methodGet = assembly.GetType("Pattern.Builder." + _dictionary["get"].Split('|')[0]).GetMethod(_dictionary["get"].Split('|')[1]);
object objGet = methodGet.Invoke(assembly.CreateInstance("Pattern.Builder." + _dictionary["get"].Split('|')[0]), null);
List<MessageModel> m = (List<MessageModel>)objGet;
// 執行 Insert 方法
MethodInfo methodInsert = assembly.GetType("Pattern.Builder." + _dictionary["insert"].Split('|')[0]).GetMethod(_dictionary["insert"].Split('|')[1]);
object objInsert = methodInsert.Invoke(assembly.CreateInstance("Pattern.Builder." + _dictionary["insert"].Split('|')[0]), new object[] { new MessageModel(_dictionary["insert"].Split('|')[2], Convert.ToDateTime(_dictionary["insert"].Split('|')[3])) });
bool b = (bool)objInsert;
return "類型為" + this._type + "的執行結果:<br />" + b.ToString() + "<br />" + m[0].Message + " " + m[0].PublishTime.ToString() + "<br />";
}
}
}
Split('|') 解析。Assembly.Load 載入組件,GetType 取得型別,GetMethod 取得方法。CreateInstance 建立實例,Invoke 執行方法並傳遞參數。GetResult() 階段。這種設計展示了建造者模式與反射技術的結合,實現了高度動態且可擴展的操作執行框架。