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.java
package 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.java
package 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.java
package 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.java
package 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(); } }The Demo class demonstrates the state pattern. First, it creates a Person object with a HappyState object. We display the results of sayHello() and sayGoodbyte() when the person object is in the happy state. Next, we change the person object's state with a SadState object. We display the results of sayHello() and sayGoodbyte(), and we see that in the sad state, the person object's behavior is different.
No comments:
Post a Comment