我正在構建一個可以在PDF文件上應用多種操作(添加文本,圖像,調整大小,裁剪等)的命令行exe。如何正確重構一些複製/粘貼代碼
目前,我的Program.cs看起來有點像這樣(它使用CommandLineParser):
switch (invokedVerb)
{
case "barcode":
Operations.BarcodeOperations.AddBarCode(options.AddBarcodeVerb);
break;
case "addblankpage":
Operations.PageOperations.AddBlankPage(options.AddBlankPageVerb);
break;
}
正如你所看到的,我的操作分成幾個XXXOperations類,他們每個人具有非常相似的指令:
public static void AddStuff(StuffOptions options)
{
Logging.Log("here is a bunch of logging");
// here sometimes there is some action-specific code but not often
using (DocWrapper doc = new DocWrapper(options.File)) // this is in all actions
{
foreach (int page in doc.GetPagesToModify(options.Pages)) // this is in most actions
{
// call some stuff on the doc instance
}
doc.Save(options.OutputFile); // this is in all actions
}
}
因此,所有的行動其網頁上創建DocWrapper的新實例,其中大部分環路(但我可以修改的行動,使他們都這樣做),和所有的人都救,但每個他們在裏面做了一系列不同的動作。
我該如何重構此代碼,以便DocWrapper實例化,頁面循環和保存位於一個位置,但我可以在循環內指定自定義代碼?
我在考慮使用委託或操作來定義我的操作,但我不知道從哪裏開始,因爲我對它們不是很熟悉。
謝謝!
你的問題是關於SO的話題,請嘗試http://codereview.stackexchange.com/ – InferOn 2014-09-04 08:25:37