简体   繁体   中英

code duplication except different class is new-ed

How can I get rid of the code duplication in my vistUpper, visitDowner, visitX... functions? the only thing different in them is the creation of new WhateverAction(params)

I can make startVisit and endVisit functions which will reduce the length of the duplication, but the duplication will still be there... I was hoping there might be a more elegant way to do this?

    virtual void visitUpper(const Potion& potion)
    {
        // leave if unavailable action for various reasons
        // and a few more things...
        PotionAction* action = new UpperAction(potion);
        actions.push_back(action);
        // add to our button list
    }
    virtual void visitDowner(const Potion& potion)
    {
        // leave if unavailable action for various reasons
        // and a few more things...
        PotionAction* action = new DownerAction(potion);
        actions.push_back(action);
        // add to our button list
    }
    //    ... and some more visitX which are identical except new XAction ...
    void actOn(int actionIndex)
    {
        actions[actionIndex]->prepareDrink();
    }

Maybe something like this:

virtual void visitUpper(const Potion& potion)
{
    CommonCode(new UpperAction(potion));
}
virtual void visitDowner(const Potion& potion)
{
    CommonCode(new DownerAction(potion));
}

You could try the following in your class:

private:
    template<typename T>
    void visit(const Potion& potion)
    {
        // leave if unavailable action for various reasons
        // and a few more things...
        PotionAction* action = new T(potion);
        actions.push_back(action);
        // add to our button list
    }

 public:

    virtual void visitUpper(const Potion& potion)
    {
        visit<UpperAction>(potion);
    }
    virtual void visitDowner(const Potion& potion)
    {
        visit<DownerAction>(potion);
    }
    // more visitXXX ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM