简体   繁体   English

小部件、服务和应用程序(类似 MVC 的架构)的 model(单例)之间的通信

[英]Communication between a widget, a service, and the model (singleton) of an application (MVC like architecture)

I got a complex question involving many different components of an application.我遇到了一个复杂的问题,涉及应用程序的许多不同组件。 I hope to be clear enough.我希望足够清楚。

In my app, the application object, a singleton, provides a model (singleton too) to many activities.在我的应用程序中,应用程序 object,一个 singleton,为许多活动提供了一个 model(也是单例)。 The main activity, presents a list of timed data to the user.主要活动,向用户呈现一个定时数据列表。 These data come from the model.这些数据来自 model。

I also have a widget and I want it to: - update when timed data is updated from within the model (via the GUI) - as time passes, update to only display the 2 first timed data of the list, removing the ones that are now obsolete.我还有一个小部件,我希望它: - 当定时数据从 model (通过 GUI)更新时更新 - 随着时间的推移,更新为仅显示列表的 2 个第一个定时数据,删除那些现在已经过时了。

To reach the second objective, I designed a service that asks the model to get some data, and uses timers to wakeup after the first data expired, and remove it from the list then sends a broadcast to the widget with some data in intent, that the widget will display.为了达到第二个目标,我设计了一个服务,它要求 model 获取一些数据,并在第一个数据过期后使用计时器唤醒,然后将其从列表中删除,然后向小部件发送一个带有一些意图数据的广播,即小部件将显示。

This works fine.这工作正常。

But I also want the widget to update as soon as data changes in the model (not because time passes, but because of the user asking for some other data through the GUI).但我也希望小部件在 model 中的数据更改后立即更新(不是因为时间流逝,而是因为用户通过 GUI 要求其他一些数据)。

But, and here is my problem:但是,这是我的问题:

how can the model tell the widget to update? model 如何告诉小部件更新? Everything is in place for the service to update the widget but the engine can not know if there is a widget.服务已准备好更新小部件,但引擎无法知道是否有小部件。 I don't want the model to call the service as maybe there is no widget and no need to have an additional process for the service.我不希望 model 调用该服务,因为可能没有小部件并且不需要为该服务添加额外的进程。

How can this interaction be redesigned elegantly?如何优雅地重新设计这种交互?

I am really missing something here.我真的在这里错过了一些东西。

You can use the Observer pattern to have the engine fire off events to whichever components in the app are interested whenever things are updated, without the event-producing component having any real knowledge of the event-consumers.您可以使用观察者模式让引擎在任何事情发生更新时向应用程序中感兴趣的任何组件触发事件,而无需事件产生组件对事件消费者有任何真正的了解。

The Event object sent as a parameter should contain all of the relevant info about the event for the UI widget to update itself, etc., so that only this abstract "event" object needs to be passed - and your layers do not bleed into each other.作为参数发送的事件 object 应包含有关 UI 小部件更新自身的事件的所有相关信息等,因此只需要传递这个抽象的“事件”object - 而且您的层不会渗入每个层其他。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM