You'll first need to determine the object(s) you'd like to apply the state pattern to and what states and transitions will be needed. Use a state diagram like the one in Head First Design Patterns if you want to visualize this properly.
2.) Write methods for the state transitions
3.) Create a class that implements State and add the state methods as specified in the interface
4.) in each state change method, you can use if/else statements to check the current state and offer different responses based on what state the object is currently in
5.) Create instance variables of type State for all your states and for the current state, which should be assigned to the state that the object should start in
6.) create a setter method that lets you set the state and a getter method so that you can get the current state
You now have a sort of rudimentary AI that can do different behaviors based on the current state.
No comments:
Post a Comment