Game Development Reference
In-Depth Information
This example shows the definition of the GameStateManager class, which is a singleton. The fact
that this is a singleton can be seen by the fact that you assign an instance of the class to
powerupjs.GameStateManager instead of the class definition itself. What is really nice is that
the class definition is now encapsulated by the namespace—it's no longer possible to access
GameStateManager_Singleton in other JavaScript files, thus ensuring that only this single instance of
the class can be used, which is exactly the point of the singleton design pattern!
The encapsulation is a result of the function enclosing the class definition. You can use this in other
ways to control what functions or classes are available where. For example, perhaps some methods
of a class are supposed to be internal (or private ). You could do this as follows:
var powerupjs = (function (powerupjs) {
...
function privateMethod(obj) {
// do something with the object
obj._currentGameState = ...;
}
GameStateManager_Singleton.prototype.publicMethod() {
privateMethod(this);
...
}
powerupjs.GameStateManager = new GameStateManager_Singleton();
return powerupjs;
})(powerupjs || {});
In this example, the method privateMethod can perform operations on the GameStateManager
instance, and it can be called from within other methods in the object, but the method isn't
accessible from other JavaScript classes.
Organizing classes in modules and folders helps provide a better feeling for the structure of a group
of related classes. Figure 23-1 shows how the powerupjs module is organized into different folders.
When you create a module, it's a good idea to provide a diagram such as the one in Figure 23-1
for the module's users. Also, because a module can consist of many different classes, you may
also want to provide some documentation that describes the module's overall philosophy. In the
case of powerupjs , it's important for users to know that the module heavily relies on a running game
loop with game objects that update and draw themselves. Furthermore, it's a good idea to provide
detailed descriptions of what each method does, what kind of parameters it expects, what calling
the method does, and any special cases. The last part of this topic discusses documentation
in more detail, and you also learn a few ways to make documentation easier to read and more
accessible to the users of your classes.
 
Search WWH ::




Custom Search