Hard
State object that triggers its own transition
What happens when this program runs?
main.cpp
class TrafficLight;
struct LightState {
virtual ~LightState() = default;
virtual void tick(TrafficLight& light) = 0;
};
class TrafficLight {
public:
explicit TrafficLight(std::unique_ptr<LightState> s) : state_(std::move(s)) {}
void setState(std::unique_ptr<LightState> s) { state_ = std::move(s); }
void tick() { state_->tick(*this); }
private:
std::unique_ptr<LightState> state_;
};
struct Yellow : LightState {
void tick(TrafficLight&) override { std::cout << "yellow\n"; }
};
struct Green : LightState {
std::string name = "green";
int ticks = 0;
void tick(TrafficLight& light) override {
if (++ticks == 2) light.setState(std::make_unique<Yellow>());
std::cout << name << " tick " << ticks << "\n";
}
};
int main() {
TrafficLight light(std::make_unique<Green>());
light.tick();
light.tick();
light.tick();
}35 of 44 in Design Patterns