Why is a static variable 'instance' necessary for Pong?

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Why is a static variable 'instance' necessary for Pong?

Ichiro
I cannot figure out the reason why a static variable is necessary for PongGame. In the PongGame.jack, a static variable 'instance' is declared and it is substituted for a local variable 'game' in the Main.jack by the following codes.

function void main(){
   var PongGame game;
   do PongGame.newInstance();
   let game = PongGame.getInstance();
....

On the other hand, a static variable is not seen in the SquareGame, where an object is generated by the following codes.

function void main(){
   var SquareGame game;
   let game = SquareGame.new();
...

Why cannot we write the Pong code just as we do for the SquareGame?

I understand that the static variable is defined at the class level and can be accessed by every object which is generated from the class. However, I cannot understand the necessity to generate and use the static variable 'instance' for Pong.

Ichiro
Reply | Threaded
Open this post in threaded view
|

Re: Why is a static variable 'instance' necessary for Pong?

WBahn
Administrator
It's possible that it could be done the same way. There's no one way to write a program and these were probably written by different people. Even if they weren't, the program structure reflects the conceptual framework that that person had in mind at that time as they developed their code.
Reply | Threaded
Open this post in threaded view
|

Re: Why is a static variable 'instance' necessary for Pong?

Ichiro
I could run the Pong program the same way as the SquareGame program without the static variable. I think a static variable is necessary when we want to use a variable that aggregates several objects. A good example in the textbook may be the variable 'total Balance', which adds all the bank balances generated from the 'BankAccount' class.
Reply | Threaded
Open this post in threaded view
|

Re: Why is a static variable 'instance' necessary for Pong?

WBahn
Administrator
Static variables have a few uses. The typical use is as a means of sharing information among all instances of a class, such as configuration data. Another is as a known location for holding information for access by things outside the class. For instance, let's say that we have a class Car and I create 15 Car objects. I could store that inventory in a dynamically allocated array of Cars in the top most function that needs it and and then pass that array around from function to function. Or, I could declare that array as a static array in the Car class and now any function that needs access to the inventory of cars simply asks the Car class for it via the static variable.

Each approach has pros and cons and it comes down to what seems best to the person writing the code at the time they write it.