设计模式,以避免不必要地添加抽象函数以适应新功能
design pattern to avoid unnecessary addition of abstract functions to accommodate new functionality
在下面的代码中,我有抽象类TestAlgModule
我将向库用户公开,他们可以使用多种功能,例如VOLUME, MIXER
等。但是,假设用户需要一个仅在MixerManager
中添加的新函数,那么我需要TestAlgModule
抽象类中添加它,现在突然所有派生类都需要添加它而没有任何好处。
如何避免这种情况?
#include <iostream>
using namespace std;
enum {VOLUME, MIXER, UNKNONWN};
class TestAlgModule {
public:
virtual void open(int type) = 0;
virtual void close(int type) = 0;
};
class volumeManager : public TestAlgModule
{
public:
void open(int type) {}
void close(int type) {}
};
class mixerManager : public TestAlgModule
{
public:
void open(int type) {}
void close(int type) {}
void differentFunction() {};
};
/* users calls this to get algModule and then call functions to get the job done */
TestAlgModule *getTestAlgModule(int type) {
switch(type) {
case VOLUME:
return new volumeManager();
case MIXER:
return new mixerManager();
default:
break;
}
return nullptr;
}
int main() {
TestAlgModule * test = getTestAlgModule(MIXER);
test->open();
//test->differentFunction(); this can't be called as it is not part of abstract class and users are exposed only abstract class
return 0;
}
如果有什么不清楚的地方,请告诉我,我会尽力回答。我正在寻找一种更好的方法来做到这一点,即VolumeManager
的变化应该独立于MixerManager
。
如果你想使用抽象工厂,就像你在上面的代码中所做的那样,那么你需要返回一个指向基类的指针。这是正确的。然后你需要通过基指针调用所有函数。
顺便说一下,请不要使用原始指针。请改用std::unique
指针。
有两种可能的解决方案。
将接口函数作为非纯函数但仍然是虚函数添加到基类中,并具有默认行为。
virtual void differentFunction() {}
由于其他纯函数,基类仍然是抽象的。这可能会导致胖接口。但在许多情况下,这是一个可以接受的解决方案。
第二种可能性是将基类指针向下转换为所需的指针,使用dynamic_cast
并检查动态强制转换的返回值。
if(mixerManager* mm = dynamic_cast<mixerManager*>(test)) {
mm->differentFunction();
}
当然,所有这些都取决于整体设计和您想要实现的目标。但以上 2 种是标准模式。
还有其他设计模式可能适合您的需求,例如构建器或原型。请检查。
相关文章:
- 如何仅为一个函数添加延迟
- 如何将带有参数的愚蠢函数添加到愚蠢的执行器中?
- "Missing type specifier - int assumed"无法通过向主函数添加"return 0"来解决
- 设计模式,以避免不必要地添加抽象函数以适应新功能
- C++泛型包装类,它为某些函数添加了额外的处理
- 将自己的函数添加到 ifstream
- 如何调用运算符函数添加两个对象?
- 为每个抽象函数定义主体后,对VTable的不确定引用
- 如何在保持多态性的同时,将成员函数添加到需要它的继承类中,而不会影响其他同级类?
- Clang在发出LLVM IR时向所有函数添加noinline属性
- [C++]向抽象日期添加天数的算法,例如,年有13个月,第13个月有40天
- 将构造函数添加到boost.python子类导致参数不匹配错误
- 我需要为返回容器副本的函数添加锁吗
- 是否可以执行范围添加更新,将线性函数添加到最大分段树中
- 将第一个虚拟函数添加到类中
- 如何告诉编译器向编译的每个函数添加一个函数调用
- Doxygen没有为函数添加文档
- 使用抽象函数时未处理的异常
- 静态多态性中的纯抽象函数等价物是什么
- 在C++中为纯虚拟/抽象函数添加主体