A
Alex
Hi, I have a problem involving some design issue.
I have two unrelated (that is, they do not derive from the same base)
classes:
ClassA
ClassB
Both have a quite similar interface, so they can be use interchangeably,
that is:
ptr = new ClassA;
ptr->f1();
ptr->f2();
To replace it with ClassB, all I need is changing the first line:
ptr = new ClassB;
ptr->f1();
ptr->f2();
(As I mentioned before, almost all the interface is identical)
This is OK when doing by hand. But I want to provide an option so a user can
toggle between both classes.
Problem is that as both classes are unrelated, I can't use a base pointer to
make instantiation..
So the most simple way I found is creating a proxy-like class, which
determines and forces the interface to be used:
class Iface {
public:
void f1();
void f2();
};
So doing:
class NewA : public ClassA, public Iface {
public:
void f1() { ClassA::f1(); }
void f2() { ClassA::f2(); }
};
and similarly
class NewB : public ClassB, public Iface {
public:
void f1() { ClassB::f1(); }
void f2() { ClassB::f2(); }
};
the I'm able to code:
Iface* ptr = new NewA;
or
Iface* ptr = new NewB;
and use them interchangeably.
Problem is -as you might have noticed- that the code to define the classes
is repetitive..
Is there a better way to solve this, and make it more elegant?
Note that in the future, I'll use ClassC with a not so similar interface. So
I find in this case the solution to be OK,
but in this specific case, maybe there's a shorter way?
Thanks.
I have two unrelated (that is, they do not derive from the same base)
classes:
ClassA
ClassB
Both have a quite similar interface, so they can be use interchangeably,
that is:
ptr = new ClassA;
ptr->f1();
ptr->f2();
To replace it with ClassB, all I need is changing the first line:
ptr = new ClassB;
ptr->f1();
ptr->f2();
(As I mentioned before, almost all the interface is identical)
This is OK when doing by hand. But I want to provide an option so a user can
toggle between both classes.
Problem is that as both classes are unrelated, I can't use a base pointer to
make instantiation..
So the most simple way I found is creating a proxy-like class, which
determines and forces the interface to be used:
class Iface {
public:
void f1();
void f2();
};
So doing:
class NewA : public ClassA, public Iface {
public:
void f1() { ClassA::f1(); }
void f2() { ClassA::f2(); }
};
and similarly
class NewB : public ClassB, public Iface {
public:
void f1() { ClassB::f1(); }
void f2() { ClassB::f2(); }
};
the I'm able to code:
Iface* ptr = new NewA;
or
Iface* ptr = new NewB;
and use them interchangeably.
Problem is -as you might have noticed- that the code to define the classes
is repetitive..
Is there a better way to solve this, and make it more elegant?
Note that in the future, I'll use ClassC with a not so similar interface. So
I find in this case the solution to be OK,
but in this specific case, maybe there's a shorter way?
Thanks.