草庐IT

c++ - 菱形继承(钻石问题) (C++)

coder 2023-05-31 原文

我知道继承钻石被认为是不好的做法。但是,我有两个案例,我觉得菱形继承(钻石问题)非常适合。我想问一下,你会推荐我在这些情况下使用菱形继承(钻石问题),还是有其他更好的设计。

案例 1: 我想在我的系统中创建代表不同类型“操作”的类。 Action 按几个参数分类:

  • Action 可以是“读”或“写”。
  • Action 可以有延迟也可以没有延迟(它不仅仅是一个参数。它会显着改变行为)。
  • Action 的“流类型”可以是 FlowA 或 FlowB。

我打算有以下设计:

// abstract classes
class Action  
{
    // methods relevant for all actions
};
class ActionRead      : public virtual Action  
{
    // methods related to reading
};
class ActionWrite     : public virtual Action  
{
    // methods related to writing
};
class ActionWithDelay : public virtual Action  
{
    // methods related to delay definition and handling
};
class ActionNoDelay   : public virtual Action  {/*...*/};
class ActionFlowA     : public virtual Action  {/*...*/};
class ActionFlowB     : public virtual Action  {/*...*/};

// concrete classes
class ActionFlowAReadWithDelay  : public ActionFlowA, public ActionRead, public ActionWithDelay  
{
    // implementation of the full flow of a read command with delay that does Flow A.
};
class ActionFlowBReadWithDelay  : public ActionFlowB, public ActionRead, public ActionWithDelay  {/*...*/};
//...

当然,我会遵守没有 2 个 Action (从 Action 类继承)将实现相同的方法。

案例 2: 我在我的系统中为“命令”实现复合设计模式。一个命令可以读、写、删除等。我也想有一个命令序列,也可以读、写、删除等。一个命令序列可以包含其他命令序列。

所以我有以下设计:

class CommandAbstraction
{
    CommandAbstraction(){};
    ~CommandAbstraction()=0;
    void Read()=0;
    void Write()=0;
    void Restore()=0;
    bool IsWritten() {/*implemented*/};
    // and other implemented functions
};

class OneCommand : public virtual CommandAbstraction
{
    // implement Read, Write, Restore
};

class CompositeCommand : public virtual CommandAbstraction
{
    // implement Read, Write, Restore
};

此外,我还有一种特殊的命令,“现代”命令。一个命令和复合命令都可以是现代的。成为“现代”会为一个命令和复合命令添加特定的属性列表(它们的属性大多相同)。我希望能够持有指向 CommandAbstraction 的指针,并根据所需的命令类型(通过 new)对其进行初始化。所以我想做下面的设计(除了上面的):

class ModernCommand : public virtual CommandAbstraction
{
    ~ModernCommand()=0;
    void SetModernPropertyA(){/*...*/}
    void ExecModernSomething(){/*...*/}
    void ModernSomethingElse()=0;

};
class OneModernCommand : public OneCommand, public ModernCommand
{
    void ModernSomethingElse() {/*...*/};
    // ... few methods specific for OneModernCommand
};
class CompositeModernCommand : public CompositeCommand, public ModernCommand
{
    void ModernSomethingElse() {/*...*/};
    // ... few methods specific for CompositeModernCommand
};

再次,我将确保没有 2 个继承自 CommandAbstraction 类的类将实现相同的方法。

谢谢。

最佳答案

继承是 C++ 中第二强(更耦合)的关系,仅次于友元。如果您可以重新设计为仅使用组合,您的代码将更加松散耦合。如果你不能,那么你应该考虑你的所有类是否真的应该从基类继承。是由于实现还是只是一个接口(interface)?您想使用层次结构中的任何元素作为基本元素吗?或者只是你的层次结构中的叶子是真正的行动?如果只有叶子是 Action 并且您正在添加行为,则可以考虑针对此类行为组合进行基于策略的设计。

这个想法是可以在小类集中定义不同的(正交的)行为,然后将它们捆绑在一起以提供真正完整的行为。在示例中,我将只考虑一个策略,该策略定义是现在还是将来执行操作,以及要执行的命令。

我提供了一个抽象类,以便模板的不同实例可以(通过指针)存储在容器中或作为参数传递给函数并以多态方式调用。

class ActionDelayPolicy_NoWait;

class ActionBase // Only needed if you want to use polymorphically different actions
{
public:
    virtual ~Action() {}
    virtual void run() = 0;
};

template < typename Command, typename DelayPolicy = ActionDelayPolicy_NoWait >
class Action : public DelayPolicy, public Command
{
public:
   virtual run() {
      DelayPolicy::wait(); // inherit wait from DelayPolicy
      Command::execute();  // inherit command to execute
   }
};

// Real executed code can be written once (for each action to execute)
class CommandSalute
{
public:
   void execute() { std::cout << "Hi!" << std::endl; }
};

class CommandSmile
{
public:
   void execute() { std::cout << ":)" << std::endl; }
};

// And waiting behaviors can be defined separatedly:
class ActionDelayPolicy_NoWait
{
public:
   void wait() const {}
};

// Note that as Action inherits from the policy, the public methods (if required)
// will be publicly available at the place of instantiation
class ActionDelayPolicy_WaitSeconds
{
public:
   ActionDelayPolicy_WaitSeconds() : seconds_( 0 ) {}
   void wait() const { sleep( seconds_ ); }
   void wait_period( int seconds ) { seconds_ = seconds; }
   int wait_period() const { return seconds_; }
private:
   int seconds_;
};

// Polimorphically execute the action
void execute_action( Action& action )
{
   action.run();
}

// Now the usage:
int main()
{
   Action< CommandSalute > salute_now;
   execute_action( salute_now );

   Action< CommandSmile, ActionDelayPolicy_WaitSeconds > smile_later;
   smile_later.wait_period( 100 ); // Accessible from the wait policy through inheritance
   execute_action( smile_later );
}

继承的使用允许通过模板实例化访问策略实现中的公共(public)方法。这不允许使用聚合来组合策略,因为不能将新的函数成员推送到类接口(interface)中。在示例中,模板依赖于具有 wait() 方法的策略,该方法对所有等待策略都是通用的。现在等待一个时间段需要一个固定的周期时间,通过 period() 公共(public)方法设置。

在示例中,NoWait 策略只是时间设置为 0 的 WaitSeconds 策略的一个特定示例。这是有意标记策略接口(interface)不需要相同。通过提供一个注册为给定事件回调的类,另一种等待策略实现可能是等待若干毫秒、时钟滴答或直到某个外部事件。

如果您不需要多态性,您可以从示例中完全取出基类和虚方法。虽然对于当前示例来说这可能看起来过于复杂,但您可以决定将其他策略添加到组合中。

虽然如果使用普通继承(使用多态性),添加新的正交行为将意味着类的数量呈指数增长,但使用这种方法,您只需分别实现每个不同的部分,然后在 Action 模板中将它们粘合在一起。

例如,您可以定期执行操作并添加退出策略来确定何时退出周期性循环。首先想到的选项是 LoopPolicy_NRuns 和 LoopPolicy_TimeSpan、LoopPolicy_Until。这个策略方法(在我的例子中是 exit())为每个循环调用一次。第一个实现在一个固定的数字(由用户固定,如上例中固定的周期)之后计算它被称为退出的次数。第二种实现将在给定的时间段内定期运行该进程,而最后一种实现将运行此进程直到给定的时间(时钟)。

如果你还跟着我到这里,我确实会做出一些改变。第一个是,不是使用实现方法 execute() 的模板参数命令,而是使用仿函数,可能还有一个模板化的构造函数,它将命令作为参数执行。基本原理是,这将使其与其他库(如 boost::bind 或 boost::lambda)结合起来更具可扩展性,因为在这种情况下,命令可以在实例化时绑定(bind)到任何自由函数、仿函数或成员方法一类的。

现在我得走了,但如果你有兴趣,我可以尝试发布修改后的版本。

关于c++ - 菱形继承(钻石问题) (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/379053/

有关c++ - 菱形继承(钻石问题) (C++)的更多相关文章

  1. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  2. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  3. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  4. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  5. ruby - Fast-stemmer 安装问题 - 2

    由于fast-stemmer的问题,我很难安装我想要的任何ruby​​gem。我把我得到的错误放在下面。Buildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingfast-stemmer:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcreatingMakefilemake"DESTDIR="cleanmake"DESTDIR=

  6. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  7. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  8. ruby-on-rails - 简单的 Ruby on Rails 问题——如何将评论附加到用户和文章? - 2

    我意识到这可能是一个非常基本的问题,但我现在已经花了几天时间回过头来解决这个问题,但出于某种原因,Google就是没有帮助我。(我认为部分问题在于我是一个初学者,我不知道该问什么......)我也看过O'Reilly的RubyCookbook和RailsAPI,但我仍然停留在这个问题上.我找到了一些关于多态关系的信息,但它似乎不是我需要的(尽管如果我错了请告诉我)。我正在尝试调整MichaelHartl'stutorial创建一个包含用户、文章和评论的博客应用程序(不使用脚手架)。我希望评论既属于用户又属于文章。我的主要问题是:我不知道如何将当前文章的ID放入评论Controller。

  9. 【高数】用拉格朗日中值定理解决极限问题 - 2

    首先回顾一下拉格朗日定理的内容:函数f(x)是在闭区间[a,b]上连续、开区间(a,b)上可导的函数,那么至少存在一个,使得:通过这个表达式我们可以知道,f(x)是函数的主体,a和b可以看作是主体函数f(x)中所取的两个值。那么可以有,  也就意味着我们可以用来替换 这种替换可以用在求某些多项式差的极限中。方法: 外层函数f(x)是一致的,并且h(x)和g(x)是等价无穷小。此时,利用拉格朗日定理,将原式替换为 ,再进行求解,往往会省去复合函数求极限的很多麻烦。使用要注意:1.要先找到主体函数f(x),即外层函数必须相同。2.f(x)找到后,复合部分是等价无穷小。3.要满足作差的形式。如果是加

  10. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

随机推荐