设计模式:我应该在这里使用继承吗?

时间:2019-04-15 22:11:27

标签: c++ inheritance design-patterns

简介/设置

我正在一个文本编辑器项目上,当前正在设置一个有效的语法荧光笔。但是我觉得我的设计方法不能很好地适用于可维护的代码。

这是语法荧光笔类的声明(不必担心“ Q”开头的特定于语言的类型;这些类型仅由Ct的Qt框架定义):

class Highlighter : public QSyntaxHighlighter
{
    Q_OBJECT

public:

    Highlighter(QTextDocument *parent = nullptr) : QSyntaxHighlighter (parent) {}
    virtual void addKeywords(QStringList keywords);
    virtual void setKeywordFormat();
    virtual void setClassPattern(QRegularExpression classPattern);
    virtual void setClassFormat();
    virtual void setFunctionPattern(QRegularExpression functionPattern);
    virtual void setFunctionFormat();
    virtual void setQuotePattern(QRegularExpression quotePattern);
    virtual void setQuoteFormat();
    virtual void setInlineCommentPattern(QRegularExpression inlineCommentPattern);
    virtual void setInlineCommentFormat();
    virtual void setBlockCommentStartPattern(QRegularExpression blockCommentStart);
    virtual void setBlockCommentEndPattern(QRegularExpression blockCommentEnd);
    virtual void setBlockCommentFormat();
    virtual void addRule(QRegularExpression pattern, QTextCharFormat format);

protected:

    virtual void highlightBlock(const QString &text) override;
    virtual void highlightMultilineComments(const QString &text);

private:

    struct HighlightingRule
    {
        QRegularExpression pattern;
        QTextCharFormat format;
    };

    QVector<HighlightingRule> rules;

    QRegularExpression blockCommentStart;
    QRegularExpression blockCommentEnd;

    QTextCharFormat keywordFormat;
    QTextCharFormat classFormat;
    QTextCharFormat inlineCommentFormat;
    QTextCharFormat blockCommentFormat;
    QTextCharFormat quoteFormat;
    QTextCharFormat functionFormat;
};

我在考虑继承的情况下将许多函数声明为虚函数。但是,是否应该使用继承确实是这个问题的核心(稍后会详细介绍)。

此外,标头还包含以下功能,这些功能不是该类的一部分:

Highlighter *cHighlighter(QTextDocument *doc);
Highlighter *cppHighlighter(QTextDocument *doc);
Highlighter *javaHighlighter(QTextDocument *doc);
Highlighter *pythonHighlighter(QTextDocument *doc);

每个功能都会组合各自的荧光笔类型。下面是函数定义:

/* Returns a Highlighter object specific to the C language and its grammar and syntax.
 */
Highlighter *cHighlighter(QTextDocument *doc)
{
    QStringList keywords;

    keywords << "\\bauto\\b" << "\\bbreak\\b" << "\\bcase\\b" << "\\bchar\\b" << "\\bconst\\b"
             << "\\bcontinue\\b" << "\\bdefault\\b" << "\\bdo\\b" << "\\bdouble\\b" << "\\belse\\b"
             << "\\benum\\b" << "\\bextern\\b" << "\\bfloat\\b" << "\\bfor\\b" << "\\bgoto\\b"
             << "\\bif\\b" << "\\bint\\b" << "\\blong\\b" << "\\bregister\\b" << "\\breturn\\b"
             << "\\bshort\\b" << "\\bsigned\\b" << "\\bsizeof\\b" << "\\bstatic\\b" << "\\bstruct\\b"
             << "\\bswitch\\b" << "\\btypedef\\b" << "\\bunion\\b" << "\\bunsigned\\b" << "\\bvoid\\b"
             << "\\bvolatile\\b" << "\\bwhile\\b";

    QRegularExpression classPattern("\\b[A-Z_][a-zA-Z0-9_]*\\b");
    QRegularExpression quotePattern("(\".*\")|('\\\\.')|('.{0,1}')");
    QRegularExpression functionPattern("\\b[A-Za-z_][A-Za-z0-9_]*(?=\\()");
    QRegularExpression inlineCommentPattern("//.*");
    QRegularExpression blockCommentStart("/\\*");
    QRegularExpression blockCommentEnd("\\*/");

    Highlighter *highlighter = new Highlighter(doc);
    highlighter->addKeywords(keywords);
    highlighter->setClassPattern(classPattern);
    highlighter->setQuotePattern(quotePattern);
    highlighter->setFunctionPattern(functionPattern);
    highlighter->setInlineCommentPattern(inlineCommentPattern);
    highlighter->setBlockCommentStartPattern(blockCommentStart);
    highlighter->setBlockCommentEndPattern(blockCommentEnd);

    return highlighter;
}


/* Returns a Highlighter object specific to the C++ language and its grammar and syntax.
 */
Highlighter *cppHighlighter(QTextDocument *doc)
{
    Highlighter *cLanguage = cHighlighter(doc);
    QStringList cppOnlyKeywords;

    cppOnlyKeywords <<  "\\basm\\b" << "\\bbool\\b" << "\\bcatch\\b" <<
                        "\\bclass\\b" << "\\bconst_cast\\b" << "\\bdelete\\b" <<
                        "\\bdynamic_cast\\b" << "\\bexplicit\\b" << "\\bfalse\\b" <<
                        "\\bfriend\\b" << "\\binline\\b" << "\\bmutable\\b" <<
                        "\\bnamespace\\b" << "\\bnew\\b" << "\\boperator\\b" <<
                        "\\bprivate\\b" << "\\bprotected\\b" << "\\bpublic\\b" <<
                        "\\breinterpret_cast\\b" << "\\bstatic_cast\\b" <<
                        "\\btemplate\\b" << "\\bthis\\b" << "\\bthrow\\b" <<
                        "\\btrue\\b" << "\\btry\\b" << "\\btypeid\\b" << "\\btypename\\b" <<
                        "\\bvirtual\\b" << "\\busing\\b" << "\\bwchar_t\\b";

    cLanguage->addKeywords(cppOnlyKeywords);
    return cLanguage;
}


/* Returns a Highlighter object specific to the Java language and its grammar and syntax.
 */
Highlighter *javaHighlighter(QTextDocument *doc)
{
    QStringList keywords;

    keywords << "\\babstract\\b" << "\\bassert\\b" << "\\bboolean\\b" << "\\bbreak\\b" << "\\bbyte\\b"
             << "\\bcase\\b" << "\\bcatch\\b" << "\\bchar\\b" << "\\bclass\\b" << "\\bconst\\b" << "\\bcontinue\\b"
             << "\\bdefault\\b" << "\\bdo\\b" << "\\bdouble\\b" << "\\belse\\b" << "\\benum\\b" << "\\bextends\\b"
             << "\\bfinal\\b" << "\\bfinally\\b" << "\\bfloat\\b" << "\\bfor\\b" << "\\bgoto\\b" << "\\bif\\b"
             << "\\bimplements\\b" << "\\bimport\\b" << "\\binstanceof\\b" << "\\bint\\b" << "\\binterface\\b"
             << "\\blong\\b" << "\\bnative\\b" << "\\bnew\\b" << "\\bpackage\\b" << "\\bprivate\\b" << "\\bprotected\\b"
             << "\\bpublic\\b" << "\\breturn\\b" << "\\bshort\\b" << "\\bstatic\\b" << "\\bstrictfp\\b" << "\\bsuper\\b"
             << "\\bswitch\\b" << "\\bsynchronized\\b" << "\\bthis\\b" << "\\bthrow\\b" << "\\bthrows\\b" << "\\btransient\\b"
             << "\\btry\\b" << "\\bvoid\\b" << "\\bvolatile\\b" << "\\bwhile\\b" << "\\btrue\\b" << "\\bfalse\\b" << "\\bnull\\b";

    QRegularExpression classPattern("\\b[A-Z_][a-zA-Z0-9_]*\\b");
    QRegularExpression quotePattern("(\".*\")|('\\\\.')|('.{0,1}')");
    QRegularExpression functionPattern("\\b[A-Za-z_][A-Za-z0-9_]*(?=\\()");
    QRegularExpression inlineCommentPattern("//.*");
    QRegularExpression blockCommentStart("/\\*");
    QRegularExpression blockCommentEnd("\\*/");

    Highlighter *highlighter = new Highlighter(doc);
    highlighter->addKeywords(keywords);
    highlighter->setClassPattern(classPattern);
    highlighter->setQuotePattern(quotePattern);
    highlighter->setFunctionPattern(functionPattern);
    highlighter->setInlineCommentPattern(inlineCommentPattern);
    highlighter->setBlockCommentStartPattern(blockCommentStart);
    highlighter->setBlockCommentEndPattern(blockCommentEnd);

    return highlighter;
}


/* Returns a Highlighter object specific to the Python language and its grammar and syntax.
 */
Highlighter *pythonHighlighter(QTextDocument *doc)
{
    QStringList keywords;

    keywords << "\\band\\b" << "\\bas\\b" << "\\bassert\\b" << "\\bbreak\\b" << "\\bclass\\b" << "\\bcontinue\\b"
             << "\\bdef\\b" << "\\bdel\\b" << "\\belif\\b" << "\\belse\\b" << "\\bexcept\\b" << "\\bFalse\\b"
             << "\\bfinally\\b" << "\\bfor\\b" << "\\bfrom\\b" << "\\bglobal\\b" << "\\bif\\b" << "\\bimport\\b"
             << "\\bin\\b" << "\\bis\\b" << "\\blambda\\b" << "\\bNone\\b" << "\\bnonlocal\\b" << "\\bnot\\b"
             << "\\bor\\b" << "\\bpass\\b" << "\\braise\\b" << "\\breturn\\b" << "\\bTrue\\b" << "\\btry\\b"
             << "\\bwhile\\b" << "\\bwith\\b" << "\\byield\\b";

    QRegularExpression classPattern("\\b[A-Z_][a-zA-Z0-9_]*\\b");
    QRegularExpression quotePattern("(\".*\")|('.*')");
    QRegularExpression functionPattern("\\b[A-Za-z_][A-Za-z0-9_]*(?=\\()");
    QRegularExpression inlineCommentPattern("#.*");
    QRegularExpression blockCommentStart("'''");
    QRegularExpression blockCommentEnd("'''");

    Highlighter *highlighter = new Highlighter(doc);
    highlighter->addKeywords(keywords);
    highlighter->setClassPattern(classPattern);
    highlighter->setQuotePattern(quotePattern);
    highlighter->setFunctionPattern(functionPattern);
    highlighter->setInlineCommentPattern(inlineCommentPattern);
    highlighter->setBlockCommentStartPattern(blockCommentStart);
    highlighter->setBlockCommentEndPattern(blockCommentEnd);

    return highlighter;
}

问题

请注意名为highlightMultilineComments的受保护方法。默认情况下,由于在Qt中如何执行语法高亮显示,因此此方法假定Highlighter的blockCommentStartblockCommentEnd正则表达式不相同。对于像Python这样的语言,显然不是这样,因为开始和结束注释的定界符是相同的(三重单引号或双引号)。在这种情况下,该功能将无法按预期执行。这就是您需要知道的全部内容。

问题继承

我将highlightMultilineComments方法虚拟化了,目的是创建一个子类,例如PythonHighlighter,该子类除了定义自定义逻辑的特定功能外,什么都不会覆盖。从理论上讲,其他语言可以覆盖所有内容并自定义它们如何设置荧光笔(如果我继承继承的话)。

但是,如果我要为Python创建一个子类,那意味着我必须为C,C ++,Java和我将来要添加的其他任何语言(为了保持一致性)创建一个子类。这显然比我目前的方法更难管理,因为我目前的方法仅具有组装荧光笔的功能。如果我为每种语言添加一个类,则源文件的数量将大大增加。

存在构建器功能的问题

因此,使用构建器功能有其好处。但是该方法不允许我重写highlightMultilineComments方法。因此在这方面显然不理想。

问题

如何在不牺牲“生成器函数”的相对可维护性的情况下,利用继承的好处-能够根据语言覆盖highlightMultilineComments之类的方法?

我考虑过的其他内容

我还考虑过添加类似highlightSymmetricMultilineComments的函数。然后,highlightMultilineComments可以检查blockCommentStartblockCommentEnd是否具有相同的正则表达式模式。如果它们确实具有相同的模式,则该函数将简单地调用其对称变量。

这是一个明显的问题,因为并非所有语言都具有对称的多行注释(Python是文本编辑器当前支持的唯一注释),所以在Highlighter中使用此注释是没有意义的。

1 个答案:

答案 0 :(得分:1)

考虑添加一个commentHighlighter成员变量,该变量代表进行实际突出显示的功能:

std::function<void(Highlighter&, const QString&)> commentHighlighter;

然后我们可以编写highlightMultilineComments,以便它调用此成员变量:

void highlightMultilineComments(const QString &text) 
{
    // If the class has a valid commentHighlighter, use that
    if(commentHighlighter) 
    {
        commentHighlighter(*this, text); 
    } 
    else //Otherwise, use the default implementation
    {
        // Default implementation
    }
}

如果您需要语言的特殊突出显示,则只需提供一个进行突出显示的功能,而不必为其创建新的类。

相关问题