java设计模式之状态模式_Java中的状态设计模式

java设计模式之状态模式

State design pattern is one of the behavioral design pattern. State design pattern is used when an Object change its behavior based on its internal state.

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

状态设计模式 (State Design Pattern)

If we have to change the behavior of an object based on its state, we can have a state variable in the Object. Then use if-else condition block to perform different actions based on the state. State design pattern is used to provide a systematic and loosely coupled way to achieve this through Context and State implementations.

如果必须根据对象的状态更改其行为,则可以在对象中使用状态变量。 然后,使用if-else条件块根据状态执行不同的操作。 状态设计模式用于通过ContextState实现提供一种系统的,松散耦合的方式来实现此目的。

State Pattern Context is the class that has a State reference to one of the concrete implementations of the State. Context forwards the request to the state object for processing. Let’s understand this with a simple example.

状态模式上下文是一类,具有引用国家的具体实现之一的国家。 上下文将请求转发到状态对象以进行处理。 让我们用一个简单的例子来理解这一点。

Suppose we want to implement a TV Remote with a simple button to perform action. If the State is ON, it will turn on the TV and if state is OFF, it will turn off the TV.

假设我们想用一个简单的按钮实现一个电视遥控器来执行操作。 如果状态为ON,则将打开电视;如果状态为OFF,则将关闭电视。

We can implement it using if-else condition like below;

我们可以使用if-else条件来实现它,如下所示;

TVRemoteBasic.java

TVRemoteBasic.java

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();
	}

}

Notice that client code should know the specific values to use for setting the state of remote. Further more if number of states increase then the tight coupling between implementation and the client code will be very hard to maintain and extend.

注意,客户端代码应该知道用于设置远程状态的特定值。 此外,如果状态数量增加,则实现和客户端代码之间的紧密耦合将很难维护和扩展。

Now we will use State pattern to implement above TV Remote example.

现在我们将使用状态模式来实现上面的电视遥控器示例。

状态设计模式接口 (State Design Pattern Interface)

First of all we will create State interface that will define the method that should be implemented by different concrete states and context class.

首先,我们将创建State接口,该接口定义应由不同的具体状态和上下文类实现的方法。

State.java

State.java

package com.journaldev.design.state;

public interface State {

	public void doAction();
}

状态设计模式的具体状态实现 (State Design Pattern Concrete State Implementations)

In our example, we can have two states – one for turning TV on and another to turn it off. So we will create two concrete state implementations for these behaviors.

在我们的示例中,我们可以有两种状态-一种用于打开电视,另一种用于关闭电视。 因此,我们将针对这些行为创建两个具体的状态实现。

TVStartState.java

TVStartState.java

package com.journaldev.design.state;

public class TVStartState implements State {

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

}

TVStopState.java

TVStopState.java

package com.journaldev.design.state;

public class TVStopState implements State {

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

}

Now we are ready to implement our Context object that will change its behavior based on its internal state.

现在,我们准备实现我们的Context对象,它将根据其内部状态更改其行为。

状态设计模式上下文实现 (State Design Pattern Context Implementation)

TVContext.java

TVContext.java

package com.journaldev.design.state;

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();
	}

}

Notice that Context also implements State and keep a reference of its current state and forwards the request to the state implementation.

注意,Context还实现了State并保留了其当前状态的引用,并将请求转发给State的实现。

状态设计模式测试程序 (State Design Pattern Test Program)

Now let’s write a simple program to test our state pattern implementation of TV Remote.

现在让我们编写一个简单的程序来测试TV Remote的状态模式实现。

TVRemote.java

TVRemote.java

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();
		
	}

}

Output of above program is same as the basic implementation of TV Remote without using state pattern.

以上程序的输出与TV Remote的基本实现相同,但不使用状态模式。

状态设计模式的好处 (State Design Pattern Benefits)

The benefits of using State pattern to implement polymorphic behavior is clearly visible. The chances of error are less and it’s very easy to add more states for additional behavior. Thus making our code more robust, easily maintainable and flexible. Also State pattern helped in avoiding if-else or switch-case conditional logic in this scenario.

使用状态模式实现多态行为的好处显而易见。 错误的机会更少,为其他行为添加更多状态非常容易。 从而使我们的代码更加健壮,易于维护和灵活。 在这种情况下,状态模式还有助于避免if-else或switch-case条件逻辑。

State Pattern is very similar to Strategy Pattern, check out Strategy Pattern in Java.

状态模式与策略模式非常相似,请查看Java中的策略模式

Thats all for State design pattern in java, I hope you liked it.

以上就是Java中的State设计模式,希望您喜欢它。

翻译自: https://www.journaldev.com/1751/state-design-pattern-java

java设计模式之状态模式

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1) 优秀的程序应该是这样的:阅读时,感觉很优雅;新增功能时,感觉很轻松;运行时,感觉很快速,这就需要设计模式支撑。2) 设计模式包含了大量的编程思想,讲授和真正掌握并不容易,网上的设计模式课程不少,大多讲解的比较晦涩,没有真实的应用场景和框架源码支撑,学习后,只知其形,不知其神。就会造成这样结果: 知道各种设计模式,但是不知道怎么使用到真实项目。本课程针对上述问题,有针对性的进行了升级 (1) 授课方式采用 图解+框架源码分析的方式,让课程生动有趣好理解 (2) 系统全面的讲解了设计模式,包括 设计模式七大原则、UML类图-类的六大关系、23种设计模式及其分类,比如 单例模式的8种实现方式、工厂模式的3种实现方式、适配器模式的3种实现、代理模式的3种方式、深拷贝等3) 如果你想写出规范、漂亮的程序,就花时间来学习下设计模式吧课程内容和目标本课程是使用Java来讲解设计模式,考虑到设计模式比较抽象,授课采用 图解+框架源码分析的方式1) 内容包括: 设计模式七大原则(单一职责、接口隔离、依赖倒转、里氏替换、开闭原则、迪米特法则、合成复用)、UML类图(类的依赖、泛化和实现、类的关联、聚合和组合) 23种设计模式包括:创建型模式:单例模式(8种实现)、抽象工厂模式、原型模式、建造者模式、工厂模式。结构型模式:适配器模式(3种实现)、桥接模式、装饰模式、组合模式、外观模式、享元模式、代理模式(3种实现)。行为型模式:模版方法模式、命令模式、访问者模式、迭代器模式、观察者模式介者模式、备忘录模式、解释器模式(Interpreter模式)、状态模式、策略模式、职责链模式(责任链模式)2) 学习目标:通过学习,学员能掌握主流设计模式,规范编程风格,提高优化程序结构和效率的能力。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值