簡體   English   中英

如何確定要使用哪個抽象類的實現?

[英]How to determine which implementation of an abstract class to use?

確定基於某個變量或定義特征來調用抽象類的哪種實現的最佳方法是什么?

代碼示例:

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
            }
        }
    }
}

我覺得好像有一種“更好”的方法可以通過使用更好的OO概念來做到這一點。 我編寫的代碼是一個示例,目的是演示我試圖理解的內容,如果有簡單的錯誤,但是有基本的想法,對不起。 我知道這是一個特定的示例,但是我認為這也適用於許多其他類型的問題。

我建議使用工廠來檢索您的處理器:

    foreach (var file in myFiles)
    {
        string extension = Path.GetExtension(file);
        IFileProcessor proc = FileProcessorFactory.Create(extension);
        // do stuff
    }

那么您的工廠就像:

public static class FileProcessorFactory 
{
    public static IFileProcessor Create(string extension) {
        switch (extension) {
            case "pdf":
                return new PdfFileProcessor();
            case "html":
                return new HtmlFileProcessor();
            // etc...
        }
    }
}

請注意,我們使用的是您的抽象類將繼承的接口。 這允許您返回任何繼承類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM