/
rgd045
/
cpp-oop-basics
Обзор
Документация
Войти
/
rgd045
/
cpp-oop-basics
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
projects/state/main.cpp
97 строк
2 KB
OMP Education
Add modules
28 июн 2024, 01:09
28 июн 2024, 01:09
0ef3df8
Код
Авторство
О чём код?
// SPDX-FileCopyrightText: 2023 Open Mobile Platform LLC <edu@omp.ru> // SPDX-License-Identifier: BSD-3-Clause #include <iostream> class AirConditioner; class State { protected: AirConditioner* m_heater; public: virtual ~State() {}; void setAirConditioner(AirConditioner* heater) { m_heater = heater; } virtual void heat() = 0; virtual void cool() = 0; virtual void on() = 0; }; class AirConditioner { private: State* m_state; public: AirConditioner(State* state): m_state{nullptr} { transitionTo(state); } ~AirConditioner() { delete m_state; } void transitionTo(State* state) { if (m_state) { delete m_state; } m_state = state; m_state->setAirConditioner(this); } void heat() { m_state->heat(); } void cool() { m_state->cool(); } void on() { m_state->on(); } }; class OnState: public State { public: void heat() { std::cout << "Heating..." << std::endl; } void cool() { std::cout << "Cooling..." << std::endl; } void on() { std::cout << "Already is on" << std::endl; } }; class OffState: public State { public: void heat() { std::cout << "Can't heat. State is off" << std::endl; } void cool() { std::cout << "Can't cool. State is off" << std::endl; } void on() { std::cout << "Power on" << std::endl; m_heater->transitionTo(new OnState); } }; int main() { AirConditioner heater {new OffState}; heater.cool(); heater.heat(); heater.on(); heater.on(); heater.cool(); heater.heat(); return 0; }