努力与多态成员的设计决定 [英] Struggling with design decision regarding polymorphic member

查看:83
本文介绍了努力与多态成员的设计决定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设计一些不依赖于投射的东西。我问了一个问题这里我相信最终有一个更好的方法,所以我征求意见。



我有一个通用的 Object

我有一个通用的 Node 对象,它包含作为成员的一个指向对象的指针。 Node 可以被子类化以提供关于如何处理它们的对象的更具体的行为以及设置什么类型子类对象特定节点正在使用。



问题是我的基类需要作为成员 Object * myObject ,以便我的应用程序可以遍历所有 Node s并调用 draw 所有 myObject 的函数。



但是如何处理在子类Object上调用自定义函数的子类Node的情况?



我考虑的一个选项是子类将其指针成员存储为 MyObjectSubclass * myObject 但是一个子类不能覆盖一个基类成员,对吧?



对于这种类型的设计,我非常感谢您更有经验的建议。

解决方案

使用接口。让每个Object子类继承自适合该类的接口,并给基类对象类一个可以检索接口的方法。



这是Microsoft的COM工作原理。 / p>

I am trying to design something that doesn't rely on casting. I asked a question here and I believe ultimately there is a better way, so I'm asking for advice.

I have a generic Object of which there will be subclasses.

I have generic Node objects which contain as a member a pointer to an Object. Nodes can be subclassed to offer more specific behaviour about how to handle their Object as well as to set what type of subclassed Object that particular node is using.

The problem is that my base class requires as a member Object * myObject so that my app can traverse all the Nodes and call a draw function on all the myObjects.

But how to handle the situation of a subclassed Node calling custom functions on a subclassed Object? These functions could be truly unique and have no place in a base class.

One option I considered is for the subclass to store its pointer member as MyObjectSubclass * myObject but a subclass cannot override a base class member, right? So that doesn't really work.

I'd appreciate a more experienced advice for this type of design.

解决方案

Work with interfaces. Have each Object child inherit from interfaces appropriate for that class, and give the base Object class a method that can retrieve the interfaces.

This is the way Microsoft's COM works.

这篇关于努力与多态成员的设计决定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆