赞
踩
场景:工作状态随时间的变化而变化
状态模式,当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类
要点:工作由状态聚合而成;将状态的变化影响抽象出来,且状态变化依赖工作类本身;抽象状态类代理了工作类
1. 抽象状态,早晨状态、中午状态、下午状态、下班状态
- package com.hj.designPattern.behavior.state;
-
- public abstract class State {
- public abstract void writeProgram(Work work);
- }
-
-
- package com.hj.designPattern.behavior.state;
-
-
- public class MorningState extends State {
- @Override
- public void writeProgram(Work work) {
- if(work.getHour()>9 && work.getHour()<=12){
- System.out.println("精神抖擞,活力满满");
- } else {
- work.setNextState(new NoonState());
- work.writeProgram();
- }
- }
- }
-
-
- package com.hj.designPattern.behavior.state;
-
- public class NoonState extends State {
- @Override
- public void writeProgram(Work work) {
- if(work.getHour()>12 && work.getHour()<=15){
- System.out.println("吃饱喝足,有点犯困");
- } else {
- work.setNextState(new AfternoonState());
- work.writeProgram();
- }
- }
- }
-
-
- package com.hj.designPattern.behavior.state;
-
- public class AfternoonState extends State {
- @Override
- public void writeProgram(Work work) {
- if(work.getHour()>15 && work.getHour()<=18){
- System.out.println("快下班了,努力工作");
- } else {
- work.setNextState(new FinishState());
- work.writeProgram();
- }
- }
- }
-
-
- package com.hj.designPattern.behavior.state;
-
- public class FinishState extends State {
- @Override
- public void writeProgram(Work work) {
- if(work.getHour()>18 && work.getHour()<=24 || work.getHour()>0 && work.getHour()<=9){
- System.out.println("下班了,休息休息,谁也不要打扰我");
- } else {
- work.setNextState(new MorningState());
- work.writeProgram();
- }
- }
- }
2. 工作类
- package com.hj.designPattern.behavior.state;
-
-
- public class Work {
- private State state;
- private int hour;
-
- Work(){
- state = new MorningState();
- }
-
- public void writeProgram(){
- state.writeProgram(this);
- }
- public void setNextState(State state){
- this.state = state;
- }
-
- public int getHour() {
- return hour;
- }
-
- public void setHour(int hour) {
- this.hour = hour;
- }
- }
3. 测试类
- package com.hj.designPattern.behavior.state;
-
- public class StateTest {
- public static void main(String[] args) {
- Work work = new Work();
- work.setHour(8);
- work.writeProgram();
-
- work.setHour(10);
- work.writeProgram();
-
- work.setHour(14);
- work.writeProgram();
-
- work.setHour(17);
- work.writeProgram();
-
- work.setHour(23);
- work.writeProgram();
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。