mardi 31 juillet 2018

Good design for a reusable class with many derived classes

I have a class that will serve as the base class for (many) other classes. The derived classes each have a slight variation in their logic around a single function, which itself will be one of a set group of external functions. I aim to have something which is efficient, clear and will result in the minimal amount of additional code per new deriving class:

Here is what I have come up with:

// ctor omitted for brevity

// CRTP
template<class DERIVED>
class Base
{
public:
    void process(batch_t &batch)
    {
        if (previous) previous->process(batch);
        pre_process(batch);
        proc.process(batch);
        post_process(batch);
    }

protected:
    // no op unless overridden
    virtual void pre_process(batch_t &batch) {}
    virtual void post_process(batch_t &batch) {}

    Processor proc;
    Base* previous;
}

  • Expose the 'process' function which follows a set pattern
  • The core logic of the function is defined by a drop in class 'Processor'
  • Allow modification of this pattern via two virtual functions, which define additional work done before/after the call to Processor::proc
  • Sometimes, this object has a handle to another which must do something else before it, for this I have a pointer 'previous'

Does this design seem good or are there some glaring holes I haven't accounted for? Or are there other common patterns used in situations like this?

Aucun commentaire:

Enregistrer un commentaire