C++观察者模式监听器事件方法/类或信号&插槽

发布于 2024-12-28 11:47:03 字数 543 浏览 3 评论 0原文

嗨,我正在我的游戏中实现 MVC,但我无法让这个东西在我的脑海中发挥作用。我将视图与游戏逻辑解耦,并将控制器解耦。事情确实有效,但我无法决定侦听器模式或信号和信号是否有效。插槽更适合我的情况。

我有基类实体,带有一些纯虚拟方法:

onEntityCreate //Called when new entity is allocated
onEntityDelete //Called when new entity is deallocated
onEntityBuild //Called on respawn or spawn
onEntityDispose //Called before respawn or deallocation
onEntityTick //called every tick when is entity "alive"
onEntityUpdate //called when entity position/orientation updates

我想在两个不同的线程中运行视图和逻辑。如果我可以在逻辑结束时分派这些事件,请勾选查看,但我不知道如何。

Hy, I am implementing MVC in my game and i can't get this thing to work in my head. I decoupled view from game logics and controller is decoupled to. Thing actually works, but i can't decide if Listener pattern or signals & slots is better for my case.

I have base class Entity with few pure virtual methods:

onEntityCreate //Called when new entity is allocated
onEntityDelete //Called when new entity is deallocated
onEntityBuild //Called on respawn or spawn
onEntityDispose //Called before respawn or deallocation
onEntityTick //called every tick when is entity "alive"
onEntityUpdate //called when entity position/orientation updates

i would like to run view and logics in two different threads. If i could dispatch these events at the end of logics tick to view but i don't know how.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

德意的啸 2025-01-04 11:47:03

根据我的经验,您应该在抽象类中使用一些混合信号/槽,主要是因为侦听器模式在 C++ 上效果不佳,因为内部类对外部类的可见性为零(例如在 Java 中),使得插入听众是一项非常艰巨的任务。所以,你可以使用伟大的 Gallant Signals,女巫是一个非常快速的实现委托/信号模式:

class EntityProvider {
public:
    Gallant::Signal0< Entity* > onEntityCreate;
};

以及在使用提供者的代码上:

void Example::bindProvider(EntityProvider* provider) {
  provider->onEntityCreate.Connect(this, &Example::onEntityCreate);
}

另外,为了获得更好的 OO 设计,您应该使用“gluer”类,该类负责将类绑定/取消绑定到其提供者。这有利于集中事件管理并避免难以调试的问题。

In my experience you should go with some hybrid Signal/Slots inside an abstract class, mainly because the Listener pattern doesn't work very well on C++ as inner classes have zero visibility over the outer class (as in Java, per example), making the insertion of listeners a very daunting task. So, you could use the great Gallant Signals, witch is a very fast implementation of the Delegate/Signal pattern:

class EntityProvider {
public:
    Gallant::Signal0< Entity* > onEntityCreate;
};

and on the code you use the provider:

void Example::bindProvider(EntityProvider* provider) {
  provider->onEntityCreate.Connect(this, &Example::onEntityCreate);
}

Also, to get a better OO design you should use a "gluer" class, that is responsible to bind/unbind classes to their providers. This is good to centralize the event management and avoid hard-to-debug problems.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文