Object Oriented Programming:Abstraction
From GPWiki
The wiki is now hosted by GameDev.NET at wiki.gamedev.net. All gpwiki.org content has been moved to the new server. However, the GPWiki forums are still active! Come say hello. [edit] AbstractionAbstraction is the process of hiding the inner workings of classes and only expose the public functions. This is sometimes descriped as designing the class to be a "black box". A class is basically a way to pack a bunch of variables and functions together so they work like a single unit. Making a class that 'is a clock' means you package variables to hold the time digits, the functions to operate the keeping of time, and the functions you need to interface with it all in one lump of code. When you want to add a clock to your bedroom, you don't care about the circuitry, cogs, or ant colonies living inside the clock. All you want to do is put it on the end table, push the buttons to set the time, and maybe turn on the alarm feature. To make a clock class, you code the circuitry, cogs, and ants in the class, then never worry about 'em again. When you want to add a clock to your program, you just create an instance of a clock. To set the time, you call one of the exposed functions designed to let you input the time. Just as it's not a good idea to set your clock with a paperclip, an exposed clockworks, and a wad of gum, it's not a good idea to let randomprogram touch the actual internal workings of your clock class. By effectively filtering input through an exposed function in the class specifically designed to take a set time request and make sure it gets done right, you ensure that things don't turn sideways on you and one morning you wake up at 37:72 y.m. and realize you're incalculably late for your watchmaking votech class. [edit] Example in C++// An example unit class class CUnit { // A bunch of function that is hidden from outside the class private: pathdata CalculatePath( int iPosX, int iPosY ); bool IsPathValid( pathdata Path ); bool CanMoveTo( int iPosX, int iPosY ); public: // An example function. This is the only function exposed from the class. bool MoveUnit( int iPosX, int iPosY ); }; bool CUnit::MoveUnit( int iPosX, int iPosY ) { // The exposed function uses a lot of private functions, // but that is hidden from the outside. pathdata ThePath = CalculatePath( iPosX, iPosY); return ( IsPathValid( ThePath ) && CanMoveTo( iPosX, iPosY ) ); } [edit] External Resources |


