views:

247

answers:

1

I'm trying to make a small Flash game that has a GUI, which is basically a menu where players can select certain items, sort of like the Tower Defense games.

Would it be a good idea to make the GUI a singleton? Because obviously there can only be 1 instance of the GUI class.

Is there a better way?

+2  A: 

In my opinion, the rest of the system should not know about your GUI, so making it a singleton is pointless. The view (GUI) should bind to some kind of models to show the current state.

In general, it's a good idea to avoid Singletons altogether.

By binding to a model I mean something like that:

class MyGUI
{
    ...
    public function set game(g:Game):void {
     g.addEventListener('pointsChanged', function(e:Event):void {
      ptsLabel.text = g.points.toString() + " points";
     })
    }
}

class Game extends EventDispatcher
{
    private var _points:int = 0;

    public function get points():int {
        return _points;
    }

    public function set points(points:int):void {
     _points = points;
     dispatchEvent(new Event('pointsChanged'));
    }
}
sharvey
Thanks for the answer :-)But I'm unsure what you mean by "The GUI should bind to some kind of model".
helloworlder
So your model is frequently going to be a Singleton in AS3 projects - it stores the various details about the state of the game. The GUI pulls information from this model but is itself just another view - you should be dispatching GUIEvents from the GUI and letting the controller implement them in your other views. Does that make sense?
Myk
This is a good answer.
Jotham
Thank you! It makes sense now.
helloworlder
You should have a look at MVC architecture, note the coupling direction: The View knows about the Model, but the Model doesn't know about the View. This View->Model coupling enables you make changes to your View without affecting the Model whatsoever.
secoif