注:我讀過this其並不完全符合我要找:從許多元素共享的XElements構建XML的最佳方式?
,我們選擇了從輸入文件構建了XML,並創建兩個輸出之一,這取決於文件的應用程序。這是一個「快速骯髒」的應用程序來解決一個直接的問題,但我知道它會找到進一步的用途,並希望通過重構來搶先。
目前我有一個「構建器」類,它接受輸入(在它的ctor中)並公開一個屬性,它是必需的XElement。但是,除了內容之外,許多XElements都是相同的,用於我的兩個XML輸出。 (呵呵,請忽略我將分別重構驗證部分)
所以我期待在曬我的應用程序的一個明智的辦法:
目前,我有這樣的事情。
public FirstBuilder(string line, int lineNumber, bool output, string subjectType, string inquiryCode)
{
var split = Regex.Split(line, @"\|");
if (split.Count() != SPLIT_COUNT)
throw new Exception("This does not appear to be a valid First Type input file.");
_lineNumber = lineNumber;
_reportId = output ? TXT_REPORT_ID : XML_REPORT_ID;
_subjectType = subjectType;
_responseType = output ? TXT_RESPONSE_TYPE : XML_REPONSE_TYPE;
_inquiryCode = inquiryCode;
_product = split[0];
_number = split[1];
_amount = split[2];
_currency = split[3];
_name = split[4];
_nationalId = split[5];
_gender = split[6];
_dateOfBirth = split[7];
_nationality = split[8];
}
public XElement RequestElement
{
get
{
return new XElement("REQUEST",
new XAttribute("REQUEST_ID", _lineNumber),
RequestParametersElement,
SearchParametersElement);
}
}
private XElement RequestParametersElement
{
get
{
return new XElement("REQUEST_PARAMETERS",
ReportParametersElement,
InquiryPurposeElement,
ApplicationElement);
}
}
private XElement ReportParametersElement
{
get
{
return new XElement("REPORT_PARAMETERS",
new XAttribute("REPORT_ID", _reportId),
new XAttribute("SUBJECT_TYPE", _subjectType),
new XAttribute("RESPONSE_TYPE", _responseType));
}
}
etc. etc...
//used by
var x = new FirstBuilder(x,y,z,etc.).RequestElement();
這一切工作,是非常快......但SecondBuilder
也使用這些相同的元素,有一些不同的人一起。
所以我正在尋找「最好」的方式來重構這些: 共享抽象類與繼承? 共享「助手」類? 擴展方法返回「構建」的元素? 每個元素的類擴展XElement的類?
我的懷疑是,這將從兩個例子中作爲一個快速解決方案在下個月的30個左右的氣球!
THX。
Thx - 是「建造者」的想法一個很好的方法來解決這個問題呢?不知道有什麼替代方法,這似乎很好地工作。 – BlueChippy 2012-02-06 04:32:03
@BlueChippy:是的,我認爲沒關係。它封裝了這個邏輯。 – 2012-02-06 08:09:06