add State pattern

This commit is contained in:
Jakub Vojvoda
2016-10-02 00:03:45 +02:00
parent aab57d0d1c
commit a5a7289085
2 changed files with 105 additions and 0 deletions

95
state/State.cpp Normal file
View File

@@ -0,0 +1,95 @@
/*
* C++ Design Patterns: State
* Author: Jakub Vojvoda [github.com/JakubVojvoda]
* 2016
*
* Source code is licensed under MIT License
* (for more details see LICENSE)
*
*/
#include <iostream>
/*
* State
* defines an interface for encapsulating the behavior associated
* with a particular state of the Context
*/
class State {
public:
virtual ~State() { /* ... */ }
virtual void handle() = 0;
// ...
};
/*
* Concrete States
* each subclass implements a behavior associated with a state
* of the Context
*/
class ConcreteStateA : public State {
public:
~ConcreteStateA() { /* ... */ }
void handle() {
std::cout << "State A handled." << std::endl;
}
// ...
};
class ConcreteStateB : public State {
public:
~ConcreteStateB() { /* ... */ }
void handle() {
std::cout << "State B handled." << std::endl;
}
// ...
};
/*
* Context
* defines the interface of interest to clients
*/
class Context {
public:
Context() : state() { /* ... */ }
~Context() {
delete state;
}
void setState(State *s) {
if (state) {
delete state;
}
state = s;
}
void request() {
state->handle();
}
// ...
private:
State *state;
// ...
};
int main()
{
State *stateA = new ConcreteStateA;
State *stateB = new ConcreteStateB;
Context *context = new Context;
context->setState(stateA);
context->request();
context->setState(stateB);
context->request();
delete context;
return 0;
}