Shadowstorm Ragnarok

The final resting place of darkness and electricity. Seriously though, just a place to talk about game development, coding, and RPGs.
HomeHome  CalendarCalendar  FAQFAQ  SearchSearch  MemberlistMemberlist  UsergroupsUsergroups  RegisterRegister  Log in  


 The Singleton

Go down 
Ion Raven
Ion Raven

Posts : 46
Join date : 2010-09-21
Age : 30

The Singleton Empty
PostSubject: The Singleton   The Singleton EmptyTue Sep 28, 2010 4:25 pm

To start off, I've yet to use this outside of making a game engine.

If you've ever had the pain of viewing any Microsoft code, you have witnessed something known as a monolith. Note that it's tons of different aspects shoved into one document and it uses global variables to keep track of everything. Sure it may work, but it's messy and very difficult to maintain and edit.

For some, the first thought is to separate the code into different files that highlight key aspects (such as the Screen, the Objects, the Graphics, the Input, etc). However at some point you may realize that some of the objects are basically holding and maintaining lists of other objects. You really only need one of these objects and more than one can cause confusion when they have to be referenced. Not only that, but these objects are referenced by different sections of programs so you have to insure their existence.

As far as I know, this is the only way to do this without global variables.

The singleton can help one keep track of objects. The trick here is the use of static in your class variables and functions. What's really key is a single static pointer to the single existence of your variable. Once you've set up your class functions as static and a static pointer to the single instance in the header (.h file), you then set the pointer to null in the source code (.cpp file). I generally keep the pointer private and create an initialize() function that creates a new instance and a terminate() function that deletes the pointer.

This is extremely useful keeping track of input. It is one object that keeps track of all the button presses and mouse movement and clicks and tracks that. (It polls every frame) Then whenever an object is updated it can check the state of the input from the object.

I will probably post a coded example eventually.

I'm the lightning in the storm. In a single unpredictable flash of chaos exerting power, resounding my presence even after I leave.
Back to top Go down
View user profile
The Singleton
Back to top 
Page 1 of 1

Permissions in this forum:You cannot reply to topics in this forum
Shadowstorm Ragnarok :: Random :: Coding-
Jump to: