23种设计模式-状态模式

状态模式:
状态设计模式是行为设计​​模式之一。 当对象根据其内部状态更改其行为时,将使用状态设计模式

角色:
● Context(环境类):环境类中维护一个State对象,他是定义了当前的状态。
● State(抽象状态类):具体状态类
● ConcreteState(具体状态类):每一个类封装了一个状态对应的行为
在这里插入图片描述

不使用状态没模式的电视剧状态

package com.journaldev.design.state;
 
public class TVRemoteBasic {
    
    
 
	private String state="";
	
	public void setState(String state){
    
    
		this.state=state;
	}
	
	public void doAction(){
    
    
		if(state.equalsIgnoreCase("ON")){
    
    
			System.out.println("TV is turned ON");
		}else if(state.equalsIgnoreCase("OFF")){
    
    
			System.out.println("TV is turned OFF");
		}
	}
 
	public static void main(String args[]){
    
    
		TVRemoteBasic remote = new TVRemoteBasic();
		
		remote.setState("ON");
		remote.doAction();
		
		remote.setState("OFF");
		remote.doAction();
	}

}

这种传统的if-else如果增加一个状态就要在原始的类增加一个分支,影响了开闭原则。
下面使用状态模式:

public interface State {
    
    
	public void doAction();
}

public class TVStartState implements State {
    
    
 
	@Override
	public void doAction() {
    
    
		System.out.println("TV is turned ON");
	}
}

public class TVStopState implements State {
    
    
 
	@Override
	public void doAction() {
    
    
		System.out.println("TV is turned OFF");
	}
}

public class TVContext implements State {
    
    
 
	private State tvState;
 
	public void setState(State state) {
    
    
		this.tvState=state;
	}
 
	public State getState() {
    
    
		return this.tvState;
	}
 
	@Override
	public void doAction() {
    
    
		this.tvState.doAction();
	}
}

package com.journaldev.design.state;
 
public class TVRemote {
    
    
 
	public static void main(String[] args) {
    
    
		TVContext context = new TVContext();
		State tvStartState = new TVStartState();
		State tvStopState = new TVStopState();
		
		context.setState(tvStartState);
		context.doAction();
		
		
		context.setState(tvStopState);
		context.doAction();
		
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_44468025/article/details/117837573