Game Object Creation – The Factory Method

This is the 4th article in the series: Building a Game Structure. Be sure to read the introduction which also has links to the rest of the articles in the series.

In previous articles we have put together a framework to handle various issues with our game. As of now, it would be quite sufficient for creating many simple games. One problem however, is that the creation of multiple types of entities in various places in our code can get cumbersome and is prone to errors and/or problems if we begin to make changes to the way we want our entities to be created

The Factory Method

The proper way to handle the creation of multiple objects with similar functionality is to use the Factory Pattern. The benefit of using a factory class to create our entities is that not only can it return a new instance of an entity to us, but it can also provide additional functionality. Our GameFactory will also create a renderer for our objects, and add any constant forces such as gravity, wind, etc. This effectively reduces the amount of things we must deal with on creation to just the one call: GameFactory.instance.getEntity( “type” );

The goal of a properly implemented factory class should be to encapsulate change. In order to do this, we identify the parts of our code that can change, and separate it from that which does not. In the case of object creation, the word “new” is a bad thing. With the factory class which I have created you can always expect to have an entity correctly instantiated by calling GameFactory.instance.getEntity( “type” ); Now, if after writing several hundred lines of code which multiple entities being instantiated all over the place I decide that each time a certain entity is created, I will also play a sound…I simply add that to the Game Factory. I do not have to worry about finding all cases where the object is created and changing it there. Now you can see where the power of the factory method comes into play.

A Barebones Example

The basic factory method would be to create a class which looks somewhat like this:

getEntity( a_type:String ) : Entity
{
	switch( a_type )
	{
		case "type1":
			return new Type1();
			break;
		case "type2":
			return new Type2();
			break;
		case "type3":
			return new Type3();
			break;
		default:
			throw new Error( "Type not recognized!" );
			break;
	}
}

The Mother of All Factories

The GameFactory that I have created is actually much more functional than that. What I have done is program all entities and renderers to a common interface, and keep the constructors matching as well. There is no proper way in Actionscript to force subclasses to follow the same constructor format, however if they do not, then a runtime error will be generated to explain the problem.

The goal of the factory class which we will be implementing is to allow us to simplify the creation of any new entities as much as possible. We will create and register entities to the GameFactory using the “EntityParams” classes. Once it is time to create new entities, we will simply call: GameFactory.instance.getEntity( “type” );

Let’s take a look at the code for our GameFactory now:

public class GameFactory
{
 
	// Game Factory is a Singleton, use this to access its methods
 	public static function get instance():GameFactory
 
	public function GameFactory( enforcer:SingletonEnforcer )
 
 	public function getEntityParams( a_type:String ) : EntityParams
        public function registerEntityType( a_params:EntityParams ) : void
 
        // These two functions are called by the classes themselves
 	public function registerGameWorld( a_gameWorld:GameWorld ) : void
 	public function registerGameWorldRenderer( a_renderer:GameWorldRenderer ) : void
 
 	// Will add a constant force to all entities of type MovingEntity
 	public function addGlobalForce( a_force:Vector2D, a_name:String ) : void
 
 	/**
 	 *  This does NOT remove the force from any entities that were created
 	 *  using it! To do that you must remove the force by calling the appropriate
 	 *  function on the entities themselves.
 	 */
 	public function removeGlobalForce( a_name:String ) : void
 
        // This is the meat and potatoes of this class. Check out the source.
 	public function getEntity( a_type:String, a_parent:Entity=null ) : Entity
 
 	// Attaches a renderer to an entity
 	public function getRenderer( a_entity:Entity, a_renderer:Class, a_data:Object ):ARenderer
}

Code Changes

I have also made some changes and improvements to existing code. Here it is:

  • Added type, customClass, rendererClass, and rendererData to EntityParams for GameFactory purposes.
  • Removed “parent” variable from EntityParams…it didn’t make sense to have it there.
  • Entity class now adds type to the id to further distinguish itself in debugging purposes.
  • All renderers now use the same constructor template.
  • GameWorld and GameWorldRenderer now activate themselves in GameFactory. ( This somewhat goes against “proper” OOD by coupling with a Singleton class, although I prefer the ease of use in this case. )
  • Altered the “Root” class to use the Timer class from GamePoetry.com for the game loop. The game loop is now more accurate.
  • Fixed an error caused with the removal / disposal of entities.

The Example

From now on, you will generally want to create a seperate file of some sort to do the initialization of your entity types. For most people this can just be a designated .as class, however other options would be to use an external .xml file or to REALLY harness the power of this sort of game structure, you could load your entities from a database. This would allow things such as user created content, or whatever you can think of.

For the example, I create a “BouncyBall” type in a seperate .as file called EntityTypes. Then for the main code, I simply initialize a couple of editable textfields and a button that changes the BouncyBall params to match what you enter. One thing that you could try out is that you could make some code that lets you register your own entity types and properties, and then another textfield that lets you type in the name of the entity you would like to spawn, and a button that creates that entity.

Final Words

I didn’t necessarily go over all of the fine details of the ACTUAL Factory Method Pattern here, so if you are curious of the exact implementation of it try searching Google, however I believe that my implementation makes object creation MUCH more flexible and robust.

Our core game structure is now quite solid, and we are moving into things such as game AI, particle effects, collisions, and other such things. The next article in the series will focus on one of these concepts, so be sure to download the new game code at the google project page and sign up for the RSS feed if you haven’t already.

1 Star2 Stars3 Stars4 Stars5 Stars (7 votes, average: 4.86 out of 5)
Loading ... Loading ...

2 Comments so far »

  1. Christian said

    am December 10 2008 @ 11:34 am

    Nice factory illustration ;)

  2. KonstantinMiller said

    am July 6 2009 @ 3:45 pm

    Hello, can you please post some more information on this topic? I would like to read more.

Comment RSS · TrackBack URI

Leave a comment

Name: (Required)

eMail: (Required)

Website:

Comment: