背景
在软件构建中,某些对象的状态如果改变,其行为也会随之发生变化,比如文档处于只读状态,其支持的行为和读写状态支持的行为可能完全不同。
特点
- 状态模式允许一个对象在其内部状态改变时改变它的行为。从而使对象看起来修改了其行为。
- State模式将所有与一个特定状态相关行为都放入一个State子类对象中,在对象状态切换时,切换相应的对象,但同时维持State的接口,这样实现了具体操作与状态转换之间的解耦。
- 为不同的状态引入不同的对象使得状态转换变得更加明确,而且可以保证不会出现状态不一致的情况,因为转换是原子性的。
- 如果State对象没有实例变量,那么各个上下文可以共享同一个State对象,从而节省开销。
//State.h
#pragma once
class Context;
class State {
public:
virtual ~State();
virtual void ChangeStateOperation(Context* context) = 0;
virtual void StateInterface(Context* context) = 0;
protected:
State();
bool ChangeState(State* state, Context* context);
};
class ConcreteStateA :public State {
public:
virtual ~ConcreteStateA();
ConcreteStateA();
virtual void StateInterface(Context* context);
virtual void ChangeStateOperation(Context* context);
};
class ConcreteStateB :public State {
public:
virtual ~ConcreteStateB();
ConcreteStateB();
virtual void StateInterface(Context* context);
virtual void ChangeStateOperation(Context* context);
};
//State.cpp
#include"Context.h"
#include"State.h"
#include<iostream>
using namespace std;
State::State() {
}
State::~State() {
}
bool State::ChangeState(State* state, Context* context) {
context->ChangeState(state);
return true;
}
ConcreteStateA::ConcreteStateA() {
}
ConcreteStateA::~ConcreteStateA() {
}
void ConcreteStateA::StateInterface(Context* context) {
cout << "StateA" << endl;
}
void ConcreteStateA::ChangeStateOperation(Context* context) {
StateInterface(context);
this->ChangeState(new ConcreteStateB(), context);
}
ConcreteStateB::ConcreteStateB() {
}
ConcreteStateB::~ConcreteStateB() {
}
void ConcreteStateB::StateInterface(Context* context) {
cout << "StateB" << endl;
}
void ConcreteStateB::ChangeStateOperation(Context* context) {
StateInterface(context);
this->ChangeState(new ConcreteStateA(), context);
}
//Context.h
#pragma once
class State;
class Context {
public:
~Context();
Context(State* state);
void StateInterface();
void ChangeStateOperation();
private:
friend class State;
bool ChangeState(State* state);
State* state;
};
//Context.cpp
#include"Context.h"
#include"State.h"
#include<iostream>
using namespace std;
Context::Context(State* state) {
this->state = state;
}
Context::~Context() {
delete state;
}
void Context::StateInterface() {
state->StateInterface(this);
}
void Context::ChangeStateOperation() {
state->ChangeStateOperation(this);
}
bool Context::ChangeState(State* state) {
this->state = state;
return true;
}
//Main.cpp
#include"Context.h"
#include"State.h"
#include<iostream>
using namespace std;
int main() {
State* state = new ConcreteStateA();
Context* context = new Context(state);
context->ChangeStateOperation();
context->ChangeStateOperation();
context->ChangeStateOperation();
delete state;
delete context;
return 0;
}
测试结果出现A-B-A的状态转换。