1。意图
当一个对象的内部状态发生变化时,允许它改变它的行为。
状态
模式变化的
位置取决于对象的状态。
两。状态图结构图
三。状态模式中的主要角色
抽象状态(状态)角色:定义一个接口来封装与环境对象的特定状态相对应的行为
特定的国家(concretestate)
作用:每一个具体的状态类实现相应的环境状态的行为(情境)。
上下文角色:定义客户机感兴趣的接口,并
保存特定状态类的实例。
四。状态模式的利与弊
1。它将与特定状态相关的行为
本地化。
2。它使状态
转换显示。
3,可以共享状态对象
五。状态模式应用场景
1。对象的行为取决于它的状态,它必须根据
运行状态在运行时改变它的行为。
2, an operation contains a large number of multi - Branch conditional statements, and these branches depend on the state of the object.This state is usually represented by one or more enumerated constants.Usually, there are multiple operations that contain the same conditional structure.The State pattern pattern puts each of the conditional branches into a separate class.This allows you to object the state of the object as an object, which can be independent of the other objects.
六、状态模式和其他模式
Singleton模式(Singleton模式):特定状态的对象通常是单身
享元模式(flyweight模式):共享模式的解释何时以及如何
分享状态对象
七。状态模式php示例
< PHP
*抽象地位角色
* /
接口状态{
*
方法示例
* /
公共
函数句柄(上下文$上下文);
}
*特定地位角色
*单级
* /
类concretestatea实现状态{
唯一的实例 / * * /
私有静态_instance美元= null;
私有函数__construct(){
}
*静态工厂方法来返回此类的惟一实例
* /
公共静态函数getInstance(){
如果(is_null(自::$ _instance)){
自::_instance美元=新concretestatea();
}
回归自我::_instance美元;
}
公共函数句柄(上下文$上下文){
echo'concrete状态
处理方法;
为背景-> setstate(concretestateb::getInstance());
}
}
*具体地位角色B
*单级
* /
类concretestateb实现状态{
唯一的实例 / * * /
私有静态_instance美元= null;
私有函数__construct(){
}
*静态工厂方法来返回此类的惟一实例
* /
公共静态函数getInstance(){
如果(is_null(自::$ _instance)){
自::_instance美元=新concretestateb();
}
回归自我::_instance美元;
}
公共函数句柄(上下文$上下文){
echo'concrete状态B处理方法;
为背景-> setstate(concretestatea::getInstance());
}
}
*环境的作用
* /
课堂语境{
私人_state美元;
*
默认状态
* /
公共
功能__construct(){
美元-> _state = concretestatea::getInstance();
}
公共功能
设置状态(状态$状态){
美元-> _state = $状态;
}
公共函数请求(){
美元_state ->处理->(美元);
}
}
*客户端
* /
客户端类{
*主
程序。
* /
公共静态函数main(){
$上下文=新上下文();
$上下文>请求();
$上下文>请求();
$上下文>请求();
$上下文>请求();
}
}
客户::主();
>
以上是利用php实现的状态模式代码,以及一些状态模式的概念
区别,希望能帮助大家
学习。