有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践

Is there a better design practice than to add a new virtual function in base that is not implemented by all derived classes

本文关键字:实现 新虚拟 虚拟 函数 更好 派生 添加 有没有 一个      更新时间:2023-10-16

我有如下所示的类层次结构。这是实际代码的简化版本。

class Base
{
public :
// user_define_type is a output parameter
virtual void Fill(user_define_type);
}
class A : public Base
{
public :
void Fill(user_define_type) override;
}
class B : public Base
{
public :
void Fill(user_define_type) override;
}

我正在重写Fill()方法,因为我需要在两个派生类中使用不同的格式。现在我必须再写一个派生自";基本;因为它具有通用功能。现在我的问题是,新类必须实现Fill(),它将在不同的用户定义类型上操作。由于我从工厂返回基类指针,所以新的CCD_ 3必须在基类中是虚拟的,但这意味着我必须在旧类中添加它的定义";A";以及";B";并从中抛出不支持的异常。这不是一个好的设计。你们有什么更好的设计建议吗?提前谢谢。

我认为您需要为您的user_defined_types创建一个公共基类来实现这一点。我还认为这可能是一个使用战略模式的好地方。

基本上,你创建

class user_defined_type_base 
{
...
}
class user_defined_type_derived : public user_defined_type_base
{
...
}
class DoSomething
{
private:
DoSomethingStrategy *strategy;
public:
DoSomething(DoSomethingStrategy *strategy) { this->strategy = strategy; }
void Fill(user_defined_type_base *type) { this->strategy->Fill(type); }
}
class DoSomethingStrategy
{
public:
virtual void Fill(user_defined_type_base *obj) = 0;
}
class DoSomethingStrategyA : public DoSomethingStrategy
{
public:
void Fill(user_defined_type_base *obj)
{
...
}
}
class DoSomethingStrategyB : public DoSomethingStrategy
{
public:
void Fill(user_defined_type_base *obj)
{
...
}
}
class DoSomethingStrategyC : public DoSomethingStrategy
{
public:
void Fill(user_defined_type_base *obj)
{
...
}
}
void main()
{
DoSomethingStrategy *strategy = new DoSomethingStragegyA();
DoSomething *dosomething = new DoSomething(strategy);
user_defined_type_base *type = new user_defined_type_base();
dosomething->Fill(type);
DoSomethingStrategy *strategyC = new DoSomethingStragegyC();
DoSomething *dosomethingC = new DoSomething(strategyC);
user_defined_type_base *typeC = new user_defined_type_derived();
dosomethingC->Fill(typeC);
}