注意:我只是在(不太可能的)情况下标记设计模式,它实际上是一个。如果不是,我会删除标签。
考虑这个例子:
template <class _base>
struct SplitPrint: public _base
{
virtual void printPositive(int positive) = 0;
virtual void printNegative(int negative) = 0;
void print( int number) override
{
_base::print(number);
if (number >= 0)
printPositive(number);
else
printNegative(number);
}
};
struct Interface
{
virtual void print( int number) = 0;
};
//implements the interface
struct NormalImplementer : public Interface
{
void print( int number) override { std::cout << number << "\n"; }
};
//Still implements the interface
struct DifferentImplementer : public SplitPrint<NormalImplementer>
{
void printPositive (int number) override { if (number > 10) std::cout << "big" << "\n"; }
void printNegative (int number) override { if (number < -10) std::cout << "small" << "\n"; }
};
//Still implements the interface
struct TellSign : public SplitPrint<DifferentImplementer>
{
void printPositive (int number) override { std::cout << "also, positive" << "\n"; }
void printNegative (int number) override { std::cout << "also, negative" << "\n"; }
};
int main()
{
NormalImplementer printer1;
DifferentImplementer printer2;
TellSign printer3;
printer1.print(5); //5
printer1.print(-42); //-42
printer2.print(5); //5
printer2.print(-42); //-42 small
printer3.print(5); //5 also, positive
printer3.print(-42); //-42 small also, negative
}
在这里,我将纯虚方法“print”拆分为另外两个方法,DifferentImplementer 不必知道如何打印一个数字(愚蠢的例子,但希望你明白我的意思)只要它知道如何打印一个正数以及如何打印负数。
这个 OOP 问题有名字吗?这个例子是用 C++ 解决这个问题的好方法吗?在 C++ 中是否有更好/更简洁的方法来解决这个问题?
最佳答案
Do this OOP problem have a name?
是的,它叫Mixin Pattern .
您一直在使用的一个相关模式是 Template Method Pattern .
Is this example a good way to solve this problem in C++?
取决于情况和用例。但这种风格本身并不糟糕,而且在许多 API 中都有使用。 Microsoft 的 ATL 就是一个例子。
is there a better/cleaner way to solve this problem in C++?
同样取决于您的用例。提供多种接口(interface)实现的方法不止一种。
关于c++ - 您如何调用位于类及其基类之间的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42537692/