我有以下类层次结构。
class Base
{
virtual void F();
}
class Derived1 : public Base
{
void F() {
cout<< " one implementation"<<endl;
}
}
class Derived2 : public Base
{
void F() {
cout<< " one implementation"<<endl;
}
}
class Derived3 : public Base
{
void F() {
cout<< " other implementation"<<endl;
}
}
class Derived4 : public Base
{
void F() {
cout<< " other implementation"<<endl;
}
}
在层次结构中引入更多类,如下所示似乎解决了问题
class Base
{
virtual void F();
}
class Base1 : public Base {
void F() {
cout<< " one implementation"<<endl;
}
}
class Base2 : public Base {
void F() {
cout<< " other implementation"<<endl;
}
}
class Derived1 : public Base1
{
}
class Derived2 : public Base1
{
}
class Derived3 : public Base2
{
}
class Derived4 : public Base2
{
}
我想知道上面几个与其他兄弟姐妹相同实施的兄弟姐妹的用例是否可以更好地解决?我在这里缺少任何明显的设计模式吗?
如果F是我想要的唯一功能,我可以通过合成来解决它(见下文)。我不知道这样做是否是一个好主意。
组合物
class Base
{
virtual void F();
}
class Base1 : public Base {
void F() {
cout<< " one implementation"<<endl;
}
}
class Base2 : public Base {
void F() {
cout<< " other implementation"<<endl;
}
}
class Derived1
{
Base * Fer;
Derived1()
{
Fer = new Base1();
}
}
class Derived2
{
Base * Fer;
Derived1()
{
Fer = new Base1();
}
}
class Derived3
{
Base * Fer;
Derived1()
{
Fer = new Base2();
}
}
class Derived4
{
Base * Fer;
Derived1()
{
Fer = new Base2();
}
}
答案 0 :(得分:0)
我会使用合成,但这样:
#include <iostream>
// define an interface
class Base
{
virtual void F() = 0;
};
// define an implementation framework which pulls in templated
// components to do the work
template<class HandleF>
struct Impl : Base
{
virtual void F() override {
f_handler(this);
}
HandleF f_handler;
};
struct OneImplementationOfF
{
template<class Self>
void operator()(Self* self) const
{
std::cout<< " one implementation"<< std::endl;
}
};
struct OtherImplementationOfF
{
template<class Self>
void operator()(Self* self) const
{
std::cout<< " other implementation"<< std::endl;
}
};
// now build our classes
class Derived1 : public Impl<OneImplementationOfF>
{
};
class Derived2 : public Impl<OneImplementationOfF>
{
};
class Derived3 : public Impl<OtherImplementationOfF>
{
};
class Derived4 : public Impl<OtherImplementationOfF>
{
};