The Strategy and State patterns are important design patterns in software development that allow for flexible and reusable code structures. The Strategy pattern defines a family of algorithms and makes them interchangeable, while the State pattern allows an object to alter its behavior when its internal state changes.
// Strategy Pattern Example
#include <iostream>
class Strategy {
public:
virtual void execute() = 0;
};
class ConcreteStrategyA : public Strategy {
public:
void execute() override {
std::cout << "Strategy A being executed." << std::endl;
}
};
class ConcreteStrategyB : public Strategy {
public:
void execute() override {
std::cout << "Strategy B being executed." << std::endl;
}
};
class Context {
private:
Strategy *strategy;
public:
Context(Strategy *s) : strategy(s) {}
void setStrategy(Strategy *s) {
strategy = s;
}
void executeStrategy() {
strategy->execute();
}
};
// State Pattern Example
class State {
public:
virtual void handle() = 0;
};
class ConcreteStateA : public State {
public:
void handle() override {
std::cout << "Handling State A." << std::endl;
}
};
class ConcreteStateB : public State {
public:
void handle() override {
std::cout << "Handling State B." << std::endl;
}
};
class ContextState {
private:
State *state;
public:
void setState(State *s) {
state = s;
}
void request() {
state->handle();
}
};
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?