Wednesday, October 2, 2013

Modules and Events

I've never really considered the implications of what object-oriented programming means before. Now, I'm considering the fact that because object-oriented allows for various divide and conquer techniques. When I wrote a simple 2D graphics program, I hard codded classes with no regard to the actual structure of the code. Since then, I've rewritten the code to take advantage of the two design patterns; the mediator pattern, and the observer pattern.

In my code, I have a single main class, the game class, that runs all the other parts of the program. Below that I have three classes; an input class, a sprite manager, and a physics manager. Within the sprite manager, I also have a sprite class. Basically, the input class generates a event whenever the left or right keys are pressed. The physics manager, in tern, is set to watch the input class for that event. When it sees that input has generated an event, it increases its velocity value in the direction of motion. If it does not see a event, it decreases the velocity by one percent. Then, if velocity is not zero, the physics manager generates a movement event. While that's going on, each member of the sprite class has been observing the physics manager, waiting to receive a movement event. Once that event is generated, the sprite class modifies its position by using the current velocity.

By using a pattern, by dividing and conquering, my code is easier to understand, simpler, and much more easy to modify. The lesson learned here is that its better to create classes and functions with one specific goal in mind, instead of trying to create a class or function that does multiple things.

No comments:

Post a Comment