存在一些场景,对象的行为受状态约束,
状态模式中,我们会创建标识各种状态的对象,
和一个行为随着状态对象的改变而改变的环境对象,
封装了不同状态转换下对象不同的行为。
可以用来替代if else。
它包含抽象状态类、具体状态类、环境类三种角色。
环境类的状态独立出去成为单独的具体状态类。
package com.example.duohoob.dp.state;
/**
* 抽象状态类-人生的阶段
* @Title: PeopleState.java
* @Package com.example.duohoob.dp.state
*
* @author yangwei
* @date 2022年7月19日
*/
public abstract class PeopleState {
abstract String getStateName();
/**
* 对象的行为
* @author yangwei
* @date 2022年7月19日
*
*/
abstract void handle();
/**
* 无论如何,饭总还是要吃的
* @author yangwei
* @date 2022年7月19日
*
*/
void eat() {
System.out.println("吃了饭");
}
}
package com.example.duohoob.dp.state;
/**
* 具体状态类-少年
* @Title: JuvenileState.java
* @Package com.example.duohoob.dp.state
*
* @author yangwei
* @date 2022年7月19日
*/
public class JuvenileState extends PeopleState {
String stateName = "少年";
@Override
String getStateName() {
// TODO Auto-generated method stub
return stateName;
}
@Override
void handle() {
// TODO Auto-generated method stub
System.out.println("上学");
}
}
package com.example.duohoob.dp.state;
/**
* 具体状态类-中年
* @Title: MidlifeState.java
* @Package com.example.duohoob.dp.state
*
* @author yangwei
* @date 2022年7月19日
*/
public class MidlifeState extends PeopleState {
String stateName = "中年";
@Override
String getStateName() {
// TODO Auto-generated method stub
return stateName;
}
@Override
void handle() {
// TODO Auto-generated method stub
System.out.println("挣钱养家");
}
}
package com.example.duohoob.dp.state;
/**
* 具体状态类-老年
* @Title: AgednessState.java
* @Package com.example.duohoob.dp.state
*
* @author yangwei
* @date 2022年7月19日
*/
public class AgednessState extends PeopleState {
String stateName = "老年";
@Override
String getStateName() {
// TODO Auto-generated method stub
return stateName;
}
@Override
void handle() {
// TODO Auto-generated method stub
System.out.println("溜达");
}
}
package com.example.duohoob.dp.state;
/**
* 环境类-人
* @Title: People.java
* @Package com.example.duohoob.dp.state
*
* @author yangwei
* @date 2022年7月19日
*/
public class People {
private String name;
public People(String name) {
this.name = name;
}
/**
* 人生的阶段
*/
private PeopleState state;
/**
* 成长-切换状态
* @author yangwei
* @date 2022年7月19日
*
* @param state
*/
void grow(PeopleState state) {
this.state = state;
}
/**
* 需要做的事
* @author yangwei
* @date 2022年7月19日
*
*/
void todo() {
System.out.println(state.getStateName() + name);
state.eat();
state.handle();
}
}
package com.example.duohoob.dp.state;
/**
* @Title: StateTest.java
* @Package com.example.duohoob.dp.state
*
* @author yangwei
* @date 2022年7月19日
*/
public class StateTest {
public static void main(String[] args) {
People people = new People("张三");
// 少年
people.grow(new JuvenileState());
people.todo();
System.out.println();
// 中年
people.grow(new MidlifeState());
people.todo();
System.out.println();
// 老年
people.grow(new AgednessState());
people.todo();
}
}
运行
