jeudi 4 août 2016

What is a good pattern to access other components' states?

I encounter a situation where component A needs to know about the state of component B when A is asked to perform certain actions (for example, if edit menu is toggled, the save action on the save button should not be performed). My application is structured like a tree with nested components.

I have tried passing all the components I need into the constructor of other components. I find this quite tedious whenever I add more component to the application, I have to pass them all the way down. Furthermore, some components are instantiated under the same constructor, but they need to know about each other. I cannot pass say component A and B into each other since I need to instantiate them in order.

I have also tried using event system to signal between components. (Observer pattern ?) It seems to be more of an overkill and not intended to be used like this.

3rd thing I try is to use singleton through dependency injection. Components register themselves on init to the provider and the provider can be injected to provide access to other components.

The 3rd approach is the most effortless and it is working for me. But I google that Singleton is not a recommended approach since it is just global variable and it entangles the code. But Unity game engine seems to have the same thing ( FindComponentByTag ). What is the general practice for this ?

Aucun commentaire:

Enregistrer un commentaire