Java设计模式:状态

状态设计模式主要用于在运行时更改状态。

状态模式的故事

人们可以以不同的财务状况生活。他们可以是富人,也可以是穷人。富国和穷国这两个国家可以不时相互转换。该示例背后的思想是:人们通常在穷人时会更努力地工作,而在富人时会更多地玩。他们的工作取决于他们所处的状态。可以根据他们的行为来改变状态,否则,社会将不公平。

状态模式类图

这是类图。您可以将其与策略模式进行比较,以更好地理解差异。
在这里插入图片描述
状态模式Java代码

下面的Java示例显示了State模式的工作方式。

State classes.

package com.programcreek.designpatterns.state;
 
interface State {
	public void saySomething(StateContext sc);
}
 
class Rich implements State{
	@Override
	public void saySomething(StateContext sc) {
		System.out.println("I'm rick currently, and play a lot.");
		sc.changeState(new Poor());
	}
}
 
class Poor implements State{
	@Override
	public void saySomething(StateContext sc) {
		System.out.println("I'm poor currently, and spend much time working.");
		sc.changeState(new Rich());
	}
}

StateContext class

package com.programcreek.designpatterns.state;
 
public class StateContext {
	private State currentState;
 
	public StateContext(){
		currentState = new Poor();
	}
 
	public void changeState(State newState){
		this.currentState = newState;
	}
 
	public void saySomething(){
		this.currentState.saySomething(this);
	}
}

Main class for testing

import com.programcreek.designpatterns.*;
 
public class Main {
	public static void main(String args[]){
		StateContext sc = new StateContext();
		sc.saySomething();
		sc.saySomething();
		sc.saySomething();
		sc.saySomething();
	}
}

结果:

I'm poor currently, and spend much time working. 
I'm rick currently, and play a lot.
I'm poor currently, and spend much time working. 
I'm rick currently, and play a lot.

在这里插入图片描述

发布了0 篇原创文章 · 获赞 0 · 访问量 91

猜你喜欢

转载自blog.csdn.net/qq_41806546/article/details/105136840