jeudi 21 janvier 2016

Design of a general-purpose handler for 'solver' class

A case where 'problem' should not be a problem in the title.

I want to implement a solver (class Solver) for a collection of problems (all children of class Problem), which more or less share the same set of methods. My current design is like this:

In solver.h:

template<class P>
class Solver{
public:
    P* p;
    Solver(P* problem) : p(problem) {}
    void justDoIt(){
        p->step1();
        p->step2();
        p->step3();
        p->step4();
        p->step5();
    }
}

In main.cpp: #include "solver.h"

class A {
public:
    void step1() {}
    void step2() {}
    void step3() {}
    void step4() {}
    void step5() {}
};

class B: public A {
public:
    void step2() {}
    void step4() {}
};

class C: public A {
public:
    void step3() {}
    void step4() {}
    void step5() {}
};

int main(){
    B b;
    C c;
    Solver<B> sb(&b);
    Solver<C> sc(&c);
    sb.justDoIt();
    sc.justDoIt();
    return 0;
}

If I want to extend Solver for a new problem type, say C, and it

  1. does nothing in step1();
  2. does step2.5() between step2() and step3()

Now calling C c; Solver<C> sc(&c); c.justDoIt(), I need to modify A, B and Solver::justDoIt() first.

Is there a scalable to design the interface that adding new problem types (all childern of A) for Solver?

PS: The current codebase I am about to modify has 47 types of problems all using the same Solver class. Minimal change is preferred.

How can I do it better?

Aucun commentaire:

Enregistrer un commentaire