• 设计模式12:状态模式


    状态模式解决的是控制一个对象状态转移的表达式过于复杂的情况,把状态的判断逻辑转移表示到不同状态的一系列类中,可以把复杂的逻辑简化。

    状态模式的好处是将特定状态的行为局部化,从而将不同状态的行为分割开来。

    将特定状态的行为都放入一个对象中,由于与状态有关的代码都存在在具体的对象类中,因此定义新的子类可以很容易的实现增加新的状态和转换。

    uml图:

    State及其子类

    public abstract class State {
    	
    	public abstract void writeProgram(Work work);
    	
    }
    
    public class BeforeNoon extends State {
    
    	@Override
    	public void writeProgram(Work work) {
    		if(work.getHour() < 12){
    			System.out.println("现在是" + Integer.toString(work.getHour())+ "点,工作!");
    		}
    		else{
    			work.setState(new Noon());
    			work.writeProgram();
    		}
    	}
    
    }
    
    public class Noon extends State {
    
    	@Override
    	public void writeProgram(Work work) {
    		if(work.getHour() < 14){
    			System.out.println("现在是" + Integer.toString(work.getHour())+ "点,午休!");
    		}
    		else{
    			work.setState(new AfterNoon());
    			work.writeProgram();
    		}
    	}
    
    }
    
    public class AfterNoon extends State {
    
    	@Override
    	public void writeProgram(Work work) {
    		if(work.getHour() < 17){
    			System.out.println("现在是" + Integer.toString(work.getHour())+ "点,工作!");
    		}
    		else{
    			work.setState(new Night());
    			work.writeProgram();
    		}
    	}
    
    }
    
    public class Night extends State {
    
    	@Override
    	public void writeProgram(Work work) {
    		if(work.isFinished()){
    			System.out.println("现在是" + Integer.toString(work.getHour())+ "点,下班!");
    		}
    		else{
    			System.out.println("现在是" + Integer.toString(work.getHour())+ "点,加班!");
    		}
    	}
    
    }
    

    Work

    public class Work {
    
    	private int hour = 0;
    	private boolean isFinished = false;
    	private State state = new BeforeNoon();
    	
    	public int getHour() {
    		return hour;
    	}
    	public void setHour(int hour) {
    		this.hour = hour;
    	}
    	public boolean isFinished() {
    		return isFinished;
    	}
    	public void setFinished(boolean isFinished) {
    		this.isFinished = isFinished;
    	}
    	
    	public State getState() {
    		return state;
    	}
    	public void setState(State state) {
    		this.state = state;
    	}
    	public void writeProgram() {
    		state.writeProgram(this);
    	}
    	
    }
    

    Demo

    public class StateDemo {
    	
    	public static void main(String[] args) {
    		Work work = new Work();
    		for(int hour = 8; hour < 22; hour++){
    			work.setHour(hour);
    			if(hour == 19){
    				work.setFinished(true);
    			}
    			work.writeProgram();
    		}
    	}
    	
    }
    

      

  • 相关阅读:
    Java中-classpath和路径的使用
    总是分不清
    Maven Web项目部署到Tomcat下问题
    一、数据设计规范
    一、入职学习
    一、服务器控件
    WebApiThrottle限流框架
    一、接口的规则
    一、免费API调用
    十、锁
  • 原文地址:https://www.cnblogs.com/zcy-backend/p/6703089.html
Copyright © 2020-2023  润新知