Flyweight

Definition: The flyweight pattern creates only one instance of a class, yet provides many "virtual" instances.

Usage: Use the flyweight pattern when you need to create many objects that are all identical. This prevents creating a bunch of excess objects, with the only drawback being that all the objects have to be identical all the time.

Example

class GameMap {
	GameMap(byte[][] aaMapChar, int mapWidth, int mapHeight) {
		//create flyweight game objects
		GameObject rock = new GameObject("rock.png");
		GameObject tree = new GameObject("tree.png");
		GameObject wall = new GameObject("wall.png");

		//create an array for the game objects
		aaGameObject = new GameObject[mapWidth][mapHeight];

		//create the game objects
		for(int x = 0; x < mapWidth; x++)
			for(int y = 0; y < mapHeight; y++)
				switch(aaMapChar[x][y]) {
				case 'r':
					aaGameObject[x][y] = rock;
					break;
				case 't':
					aaGameObject[x][y] = tree;
					break;
				case 'w':
					aaGameObject[x][y] = wall;
					break;
				}
	}

	GameObject[][] aaGameObject
}

There is little point in allocating mapWidth * mapHeight GameObjects when there are really only 3 different objects. If each GameObject loads an image, mapWidth * mapHeight images would probably be too much for video memory.

Index

Copyright (C) 2008 Steven Fletcher. All rights reserved.