状态模式允许一个对象在其内部状态改变的时候改变其行为。这个对象看上去就像是改变了它的类一样。状态模式由抽象状态类(定义状态方法),具体状态类(实现具体的状态方法,改变内部状态,同时按条件改变和状态管理类的状态对象)和状态管理类(存储状态类对象)组成,比如人的一生,在各个阶段的状态,随着年龄增长而改变。
示例:
public class State {
public static void main(String[] args){
State state=new State();
StateManager stateManager=state.new StateManager();
stateManager.setState(state.new Child());
}
abstract class PersonState{
protected int startAge,endAge;
public PersonState(int startAge,int endAge) {
this.startAge = startAge;
this.endAge = endAge;
}
abstract void grow(StateManager manager);
abstract void feature();
}
class Child extends PersonState{
public Child() {
super(0, 6);
}
@Override
void grow(StateManager manager) {
while (true) {
startAge++;
if (startAge > endAge) {
manager.setState(new Student());
break;
}
feature();
}
}
@Override
void feature() {
System.out.println("我是个小屁孩,现在"+startAge+"岁,玩就是了");
}
}
class Student extends PersonState{
public Student() {
super(7,22);
}
@Override
void grow(StateManager manager) {
while (true) {
startAge++;
if (startAge > endAge) {
manager.setState(new Adult());
break;
}
feature();
}
}
@Override
void feature() {
System.out.println("我是个学生,现在"+startAge+"岁,学得头都大了");
}
}
class Adult extends PersonState{
public Adult() {
super(23, 40);
}
@Override
void grow(StateManager manager) {
while (true) {
startAge++;
if (startAge > endAge) {
manager.setState(new Middle());
break;
}
feature();
}
}
@Override
void feature() {
System.out.println("我是个加班狗,现在"+startAge+"岁,没钱没时间,苦逼");
}
}
class Middle extends PersonState{
public Middle() {
super(41, 60);
}
@Override
void grow(StateManager manager) {
while (true) {
startAge++;
if (startAge > endAge) {
manager.setState(new Elderly());
break;
}
feature();
}
}
@Override
void feature() {
System.out.println("我是个中年人,现在"+startAge+"岁,有点钱了,压力还是大啊");
}
}
class Elderly extends PersonState{
public Elderly() {
super(61, 100);
}
@Override
void grow(StateManager manager) {
while (true) {
startAge++;
if (startAge > endAge) {
System.out.println("死啦死啦,活够了");
break;
}
feature();
}
}
@Override
void feature() {
System.out.println("我是个老年人,现在"+startAge+"岁,遛遛狗,下下棋,等死");
}
}
class StateManager{
private PersonState state;
public void setState(PersonState state) {
this.state = state;
this.state.feature();
this.state.grow(this);
}
}
}
网友评论