状态模式
1. 定义
状态模式允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它的类。
2. 类图
3. Example
下面定义了一个State接口,接口里有个meaningOfLife的方法,定义了出生、三十、四十、五十、顿悟的几种状态。
人的主体PersonContext成员变量有State和感受(feeling)方法,测试代码中setAge来模拟人生阶段的变化,两次调用feeling略显不合理。。。
package com.gitlearning.hanldegit.patterns.state;
public interface State {
void meaningOfLife(PersonContext personContext);
}
class Born implements State {
@Override
public void meaningOfLife(PersonContext personContext) {
if (personContext.getAge() == 0) {
System.out.println("Cry...");
} else {
personContext.setState(new Thirty());
}
}
}
class Thirty implements State {
@Override
public void meaningOfLife(PersonContext personContext) {
if (personContext.getAge() <= 30) {
System.out.println("三十而立");
} else {
personContext.setState(new Fourty());
}
}
}
class Fourty implements State {
@Override
public void meaningOfLife(PersonContext personContext) {
if (personContext.getAge() <= 40) {
System.out.println("四十而不惑");
} else {
personContext.setState(new Fifty());
}
}
}
class Fifty implements State {
@Override
public void meaningOfLife(PersonContext personContext) {
if (personContext.getAge() <= 50) {
System.out.println("五十而知天命");
} else {
personContext.setState(new Hit());
}
}
}
class Hit implements State {
@Override
public void meaningOfLife(PersonContext personContext) {
System.out.println("处世若大梦,胡为劳其生");
}
}
package com.gitlearning.hanldegit.patterns.state;
import lombok.Data;
@Data
public class PersonContext {
// 人生状态
State state;
int age;
public void feeling() {
state.meaningOfLife(this);
}
public void setAge(int age) {
this.age = age;
// 这里纯粹是为了改变一下状态
feeling();
}
public PersonContext() {
state = new Born();
}
}
class Test {
public static void main(String[] args) {
PersonContext personContext = new PersonContext();
personContext.feeling();
personContext.setAge(30);
personContext.feeling();
personContext.setAge(40);
personContext.feeling();
personContext.setAge(50);
personContext.feeling();
personContext.setAge(60);
personContext.feeling();
}
}
输出:
Cry...
三十而立
四十而不惑
五十而知天命
处世若大梦,胡为劳其生
当你准备好了,机会来临的时候,你才能抓住