ScreenManager button handling

Hello everyone,

I am currently trying to come up with a barebones architecture for small sample demos. I have just written a ScreenManager that keeps a stack of Screens and updates/draws them as necesarry. This works really well so far.

I have a simple movement demo and would like to try and make a Pausescreen and a continue button. I have implemented said screen and button now, but I am not sure how to handle the button click, my problem is the following:

The button lives on a MenuScreen which in turn lives in the stack within the ScreenManager. Basically, we have this (simplified) relation:

ScreenManager <— MenuScreen <— Button

My issue is now, how is the button living inside the MenuScreen, which in turn lives inside the ScreenManager, going to inform the ScreenManager to remove/add screens as wanted? I heard about the observer pattern but I am not sure if that is doing the trick and I am also not quite sure what this implies as of yet.

But is it possible, maybe over a third instance, to communicate between the buttons and the ScreenManager? Sorry if this question is a little vague, this is for a project so I don’t want to share the code to not violate any rules, but I just would be happy about a general pointer to a direction that could help me climb this wall. I want to avoid going the Singleton route because I heard that can cause more problems than help.

Thanks a lot!

You could use callbacks. You will have to add a delegate in your button class or whatever widget class it inherits from. That delegate is then called when the button is pushed. You can then subscribe a callback method to the button that informs the screenManager that the button has been pushed.
It could look something like this:

var manager = new ScreenManager();
var menu = new Menu();
var button = new Button();

manager.addWidget(menu);
menu.addWidget(button);

button.onClick += () => {
    manager.addScreen();
};