行为型-状态模式

该代码示例展示了如何使用状态模式来处理销售出库单的不同状态(新建、待审批、已审批、已完成)。Context类持有一个State接口的实例,并根据状态类型切换到不同的状态类(NewState,ApprovingState,ApprovedState,FinishedState),每个状态类实现了execute方法,执行对应状态的逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class StatePatternDemo {
	
	public static void main(String[] args) {
		Context context = new Context(new NewState());
		context.execute(1); 
		context.execute(2); 
		context.execute(3); 

	}
	
	public interface State {
		
		void execute();
		
	}
	
	public static class NewState implements State {

		@Override
		public void execute() {
			System.out.println("执行销售出库单新建状态的逻辑");  
		}
		
	}
	
	public static class ApprovingState implements State {

		@Override
		public void execute() {
			System.out.println("执行销售出库单待审批状态的逻辑");  
		}
		
	}
	
	public static class ApprovedState implements State {

		@Override
		public void execute() {
			System.out.println("执行销售出库单已审批状态的逻辑");  
		}
		
	}
	
	public static class FinishedState implements State {

		@Override
		public void execute() {
			System.out.println("执行销售出库单已完成状态的逻辑");  
		}
		
	}
	
	public static class Context {
		
		private State state;
		
		public Context(State state) {
			this.state = state;
			this.state.execute();
		}
		
		public void execute(int stateType) {
			if(stateType == 1) {
				this.state = new ApprovingState();
				this.state.execute();
			} else if(stateType == 2) {
				this.state = new ApprovedState();
				this.state.execute();
			} else if(stateType == 3) {
				this.state = new FinishedState();
				this.state.execute();
			}
		}
		
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码海拾贝2023

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值