HeadFirstデザパタ 第10章 State をC++で実装
自分のお勉強用 : HeadFirstデザパタ 第10章 State をC++で適当に実装
おさらい。
とりあえずStateAとBを順繰りに入れ替えるようなやつ。
お手本を真面目に写経するのは冗長なのでパス。
とりあえずStateAとBを順繰りに入れ替えるようなやつ。
お手本を真面目に写経するのは冗長なのでパス。
ファイル一覧
- State.h : インターフェイス
- StateA.h と StateA.cpp : 実装
- State.h と StateB.cpp : 実装
- GumballMachine.h と cpp
- state_cpp.cpp : メインクラス
実装
State.h : インターフェイス
- #ifndef STATE_H
- #define STATE_H
- class State
- {
- public:
- virtual ~State() {}
- virtual void methodA() = 0;
- virtual void methodB() = 0;
- };
- #endif // !STATE_H
StateA.h
- #ifndef STATE_A_H
- #define STATE_A_H
- #include "State.h"
- #include "GumballMachine.h"
- class StateA : public State
- {
- friend class GumballMachine;
- public:
- StateA(GumballMachine* gm):gm_(gm) {}
- virtual void methodA() ;
- virtual void methodB() ;
- private:
- GumballMachine* gm_;
- };
- #endif // !STATE_A_H
StateA.cpp
- #include "StateA.h"
- #include
using namespace std; void StateA::methodA() { cout << "StateA::MethodA" << endl; } void StateA::methodB() { cout << "StateA::MethodB" << endl; gm_->setState( gm_->getStateB() ); cout << "StateChange : A -> B" << endl; }
StateB.h
- #ifndef STATE_B_H
- #define STATE_B_H
- #include "State.h"
- #include "GumballMachine.h"
- class StateB : public State
- {
- friend class GumballMachine;
- public:
- StateB(GumballMachine* gm):gm_(gm) {}
- virtual void methodA() ;
- virtual void methodB() ;
- private:
- GumballMachine* gm_;
- };
- #endif // !STATE_B_H
StateB.cpp
- #include "StateB.h"
- #include
using namespace std; void StateB::methodA() { cout << "BBB::AAA" << endl; } void StateB::methodB() { cout << "BBB::BBB" << endl; gm_->setState( gm_->getStateA() ); cout << "StateChange : B -> A" << endl; }
GumballMachine.h
- #ifndef GUMBALL_MACHINE_H
- #define GUMBALL_MACHINE_H
- #include "State.h"
- class GumballMachine
- {
- public:
- GumballMachine();
- ~GumballMachine();
- void eventA() { state_->methodA(); }
- void eventB() { state_->methodB(); }
- void setState(State* s) { state_ = s; }
- State* getStateA() { return sa; }
- State* getStateB() { return sb; }
- private:
- State* state_;
- State* sa;
- State* sb;
- };
- #endif // !GUMBALL_MACHINE_H
GumballMachine.cpp
- #include "GumballMachine.h"
- #include "StateA.h"
- #include "StateB.h"
- GumballMachine::GumballMachine() {
- sa = new StateA(this);
- sb = new StateB(this);
- state_ = sa;
- }
- GumballMachine::~GumballMachine()
- {
- delete sa;
- delete sb;
- }
state_cpp.cpp
- #include "GumballMachine.h"
- int main()
- {
- GumballMachine gm;
- for (int i = 0; i < 3; i++) {
- gm.eventA();
- gm.eventB();
- }
- }
所感
ステータス周りはFlyweight的な意味でStaticでやってもよいし、Stateのメソッド部分はコマンドパターンを当ててもよいね。
コメント
コメントを投稿