平時寫程序時,總少不了對某個被分裝的很好的類中的成員變量進行訪問,所以會寫一些:
? void T::setXxx(Yyy v) {}
? Yyy?T::getXxx() const
這樣的代碼,因為T類中有個Yyy類型的xxx成員變量,當有幾個這樣的成員變量需要寫訪問函數時,好多的函數定義真是讓人煩透了,就算使用提供了方便模板的ide,也令人心煩,所以我有了以下想法,其實現實中的好多項目里早已運用了,這里只是提一下,如下代碼:
struct State {
? union {
??? int intV_;
??? bool boolV_;
??? char* rawStrV_;
??? // other members
? };

? State(const int v) : intV_(v) {}
? State(const bool v) : boolV_(v) {}
? State(const char* v) : rawStrV_() {}
? // other ctors
};

enum StateType{
? ST_WINDOWED,
? ST_ACTIVED,
? ST_WIDTH,
? ST_HEIGHT,
? ST_VERSION
};

class Renderer {
public:
? void setState(StateType st, State v) {
??? switch(st) {
????? case ST_WINDOWED:
????? { // ...
????? }break;
????? case ST_ACTIVED:
????? { // ...
????? }break;
????? // ...
????? default: assert(false);
??? }
? }
? State getState(StateType st) const {
??? switch(st) {
????? default:
????? case ST_WINDOWED: return windowed_;
????? case ST_ACTIVED: return actived_;
????? // ...
??? }
? }
private:
? int w;
? int h;
? char* versionDescription_;
? bool windowed_;
? bool actived_;
};

非常簡單明了?。?!
優點:還是有些繁瑣,但不用寫一堆的函數定義體“{}”,這里只有兩對;容易產生高效的代碼
缺點:更改代碼時,代碼改動量較大
可以看出,這一管理策略正好與“狀態管理”的接口語義一致,使人感覺非常輕量。