State Pattern
Author: Deron Eriksson
Description: This Java tutorial describes the state pattern, a behavioral object pattern.
Tutorial created using:
Windows Vista || JDK 1.6.0_11 || Eclipse JEE Ganymede SR1 (Eclipse 3.4.1)
The state pattern is a behavioral object design pattern. The idea behind the state pattern is for an object to change its behavior depending on its state. In the state pattern, we have a Context class, and this class has a State reference to a Concrete State instance. The State interface declares particular methods that represent the behaviors of a particular state. Concrete States implement these behaviors. By changing a Context's Concrete State, we change its behavior. In essence, in the state pattern, a class (the Context) is supposed to behave like different classes depending on its state. The state pattern avoids the use of switch and if statements to change behavior. Let's look at an example of the state pattern. First off, we'll define the EmotionalState interface. It declares two methods, sayHello() and sayGoodbye(). EmotionalState.javapackage com.cakes; // State public interface EmotionalState { public String sayHello(); public String sayGoodbye(); } The HappyState class is a Concrete State that implements sayHello() and sayGoodbye() of EmotionalState. These messages are cheerful (representing a happy state). HappyState.javapackage com.cakes; // Concrete State public class HappyState implements EmotionalState { @Override public String sayGoodbye() { return "Bye, friend!"; } @Override public String sayHello() { return "Hello, friend!"; } } The SadState class also implements the EmotionalState interface. The messages are sad (representing a sad state). SadState.javapackage com.cakes; //Concrete State public class SadState implements EmotionalState { @Override public String sayGoodbye() { return "Bye. Sniff, sniff."; } @Override public String sayHello() { return "Hello. Sniff, sniff."; } } The Person class is the Context class. It contains an EmotionalState reference to a concrete state. In this example, we have Person implement the EmotionalState reference, and we pass the calls to Person's sayHello() and sayGoodbye() methods on to the corresponding methods on the emotionalState reference. As a result of this, a Person object behaves differently depending on the state of Person (ie, the current EmotionalState reference). Person.javapackage com.cakes; // Context public class Person implements EmotionalState { EmotionalState emotionalState; public Person(EmotionalState emotionalState) { this.emotionalState = emotionalState; } public void setEmotionalState(EmotionalState emotionalState) { this.emotionalState = emotionalState; } @Override public String sayGoodbye() { return emotionalState.sayGoodbye(); } @Override public String sayHello() { return emotionalState.sayHello(); } } (Continued on page 2) Related Tutorials:
|