State

Definition: The State pattern allows an object to alter its behavior when its internal state changes.

Usage: The State pattern is essentially an alternative to having a bunch of conditionals in some code. It moves the code for each conditional into a separate class. The resulting code is much cleaner and even marginally faster (one method call is faster than a ton of conditionals).

Example

enum AlienAi {
	MOVE_LEFT() {
		State move() {
			move left
			if has hit wall
				return MOVE_RIGHT
			else
				return MOVE_LEFT
		}
	}
	MOVE_RIGHT() {
		State move() {
			move right
			if has hit wall
				return MOVE_LEFT
			else
				return MOVE_RIGHT
		}
	}

	State move()
}

class Alien {
	move() {
		state = state.move()
	}

	State state = AlienAi.MOVE_LEFT
}

These classes model an alien that moves back and forth like the aliens in Space Invaders. The different states need not be stored in an enum as above.

Index

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