From a5a72890859cabd9b4081d44dcb8a6594e6be4be Mon Sep 17 00:00:00 2001 From: Jakub Vojvoda Date: Sun, 2 Oct 2016 00:03:45 +0200 Subject: [PATCH] add State pattern --- state/README.md | 10 ++++++ state/State.cpp | 95 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+) create mode 100644 state/README.md create mode 100644 state/State.cpp diff --git a/state/README.md b/state/README.md new file mode 100644 index 0000000..1b1fcd2 --- /dev/null +++ b/state/README.md @@ -0,0 +1,10 @@ +## State + +The pattern allows an object to alter its behavior when its internal state changes. +The object will appear to change its class. It has behavioral purpose and applies +to the objects. + +### When to use + +* when an object's behavior depends on its state, and it must change its behavior at run-time depending on that state +* operations have large, multipart conditional statements that depend on the object's state \ No newline at end of file diff --git a/state/State.cpp b/state/State.cpp new file mode 100644 index 0000000..21087c6 --- /dev/null +++ b/state/State.cpp @@ -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 + +/* + * 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; +}