//
// Created by win10 on 2021/11/16.
//
#include <thread>
#include <iostream>
#include <vector>
using namespace std;
/*
* 状态模式
* 当一个对象的行为取决于它自己的状态, 并且它必须在运行时刻根据状态改变它自己的行为
*/
class Work;
class ForenoonState;
class NoonState;
class State {
public:
virtual void writeProgram(Work* work) = 0;
};
class Work {
public:
void setState(State* state) {
this->currentState = state;
}
void writeProgram() {
this->currentState->writeProgram(this);
}
int hour;
private:
State* currentState;
};
class NoonState: public State {
public:
virtual void writeProgram(Work* work) {
if(work->hour < 13) {
std::cout << "NoonState writeProgram, work->hour < 13" << std::endl;
} else {
std::cout << "NoonState writeProgram, work->hour >= 13" << std::endl;
}
}
};
class ForenoonState: public State {
public:
virtual void writeProgram(Work* work) {
if(work->hour < 12) {
std::cout << "ForenoonState writeProgram, work->hour < 12" << std::endl;
} else {
std::cout << "ForenoonState writeProgram, work->hour >= 12" << std::endl;
work->setState(new NoonState());
work->writeProgram();
}
}
};
int main() {
Work* mywork =new Work();
mywork->hour = 9;
mywork->writeProgram();
mywork->hour = 14;
mywork->writeProgram();
return 0;
}
量化交易之设计模式篇 - 状态模式
最新推荐文章于 2024-08-19 21:22:29 发布