根據某個變量或定義特徵來確定抽象類的哪個實現需要調用的最佳方法是什麼?如何確定要使用哪個抽象類的實現?
代碼示例:
public abstract class FileProcesser
{
private string _filePath;
protected FileProcessor(string filePath)
{
if (filePath == null)
{
throw new ArgumentNullException("filePath");
}
// etc etc
_filePath = filePath;
}
// some example methods for this file
public abstract int GetFileDataCount();
public abstract IEnumerable<FileItem> GetFileDataItems();
}
// specific implementation for say, a PDF type of file
public class PdfFileProcesser : FileProcessor
{
public PdfFileProcessor(string filePath) : base(filePath) {}
// implemented methods
}
// specific implementation for a type HTML file
public class HtmlFileProcessor : FileProcessor
{
public HtmlFileProcessor(string filePath) : base(filePath) {}
// implemented methods
}
public class ProcessMyStuff()
{
public void RunMe()
{
// the code retrieves the file (example dummy code for concept)
List<string> myFiles = GetFilePaths();
foreach (var file in myFiles)
{
if (Path.GetExtension(file) == ".pdf")
{
FileProcessor proc = new PdfFileProcessor(file);
// do stuff
}
else if (Path.GetExtension(file) == ".html")
{
FileProcessor proc = new HtmlFileProcessor(file);
// do stuff
}
// and so on for any types of files I may have
else
{
// error
}
}
}
}
我覺得好像有一個「聰明」的方式配合使用,更好地面向對象的概念來做到這一點。我編寫的代碼是一個示例,用於說明我想要理解的內容,如果存在簡單的錯誤但基本思想存在,則很抱歉。我知道這是一個具體的例子,但我認爲這也適用於許多其他類型的問題。
看看「抽象工廠模式」。 – EkoostikMartin
這幾乎是工廠的基本情況。 http://www.dotnetperls.com/factory –
您似乎正在實施戰略模式。我更傾向於創建一個Processor類,它包含一個IProcessFiles接口,該接口定義所涉及的基本方法,併爲每種類型單獨運行處理器,每個處理器只查找可處理的文件類型。這可能效率較低,但它更乾淨。 – Magus