大话设计模式-状态模式(大鸟和小菜Java版)
Posted 香风智乃哈~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了大话设计模式-状态模式(大鸟和小菜Java版)相关的知识,希望对你有一定的参考价值。
正在学习大话设计模式,把书上的代码转换成Java来进行实现,
工作状态-状态模式版的Java代码
状态模式:当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类
package 设计模式.状态模式;
//先定义一个接口,当然也可以是一个抽象类,作用是一样的
public interface State {
public void writeProgram(Work work);
}
package 设计模式.状态模式;
//我把一天所有的状态类都写在一块了
public class ForenoonState implements State{
@Override
public void writeProgram(Work work) {
if(work.getHour() < 12){
System.out.println("当前时间:"+work.getHour()+"点 上午工作,精神百倍");
}else{
work.setCurrent(new NoonState());
work.writeProgram();
}
}
}
class NoonState implements State{
@Override
public void writeProgram(Work work) {
if(work.getHour() < 13){
System.out.println("当前时间:"+work.getHour()+"点 饿了,午饭,犯困,午休");
}else{
work.setCurrent(new AfternoonState());
work.writeProgram();
}
}
}
class AfternoonState implements State{
@Override
public void writeProgram(Work work) {
if(work.getHour() < 17){
System.out.println("当前时间:"+work.getHour()+"点 下午状态还不错,继续摸鱼");
}else{
work.setCurrent(new EveningState());
work.writeProgram();
}
}
}
class EveningState implements State{
@Override
public void writeProgram(Work work) {
if(work.isFinish()){
work.setCurrent(new RestState());
work.writeProgram();
}else{
if(work.getHour() < 21){
System.out.println("当前时间:"+work.getHour()+"点 加班啊,看会儿动漫先");
}else{
work.setCurrent(new SleepingState());
work.writeProgram();
}
}
}
}
class SleepingState implements State{
@Override
public void writeProgram(Work work) {
System.out.println("当前时间:" + work.getHour() + "点 扛不住了,不行,再熬会儿再睡");
}
}
class RestState implements State{
@Override
public void writeProgram(Work work) {
System.out.println("当前时间:" + work.getHour() + "点 下班回家了");
}
}
package 设计模式.状态模式;
//这个是工作类,此时没有过长的分支判断语句
public class Work {
private int hour;
private boolean finish = false;
private State current;
public Work() {
current = new ForenoonState();
}
public void writeProgram(){
current.writeProgram(this);
}
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public boolean isFinish() {
return finish;
}
public void setFinish(boolean finish) {
this.finish = finish;
}
public State getCurrent() {
return current;
}
public void setCurrent(State current) {
this.current = current;
}
}
package 设计模式.状态模式;
//测试主类,主要测试不同时间点,测试对象的状态
public class Test {
public static void main(String[] args) {
Work work = new Work();
work.setHour(9);
work.writeProgram();
work.setHour(10);
work.writeProgram();
work.setHour(12);
work.writeProgram();
work.setHour(13);
work.writeProgram();
work.setHour(14);
work.writeProgram();
work.setHour(17);
work.setFinish(false);
work.writeProgram();
work.setHour(19);
work.writeProgram();
work.setHour(22);
work.writeProgram();
}
}
输出效果:
以上就是状态模式的Java代码实现
参考的大佬文章:https://blog.csdn.net/MONKEY_D_MENG/article/details/5707706
以上是关于大话设计模式-状态模式(大鸟和小菜Java版)的主要内容,如果未能解决你的问题,请参考以下文章