平時(shí)寫程序時(shí),總少不了對(duì)某個(gè)被分裝的很好的類中的成員變量進(jìn)行訪問,所以會(huì)寫一些:
? void T::setXxx(Yyy v) {}
? Yyy?T::getXxx() const
這樣的代碼,因?yàn)門類中有個(gè)Yyy類型的xxx成員變量,當(dāng)有幾個(gè)這樣的成員變量需要寫訪問函數(shù)時(shí),好多的函數(shù)定義真是讓人煩透了,就算使用提供了方便模板的ide,也令人心煩,所以我有了以下想法,其實(shí)現(xiàn)實(shí)中的好多項(xiàng)目里早已運(yùn)用了,這里只是提一下,如下代碼:
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_;
};
非常簡單明了!!!
優(yōu)點(diǎn):還是有些繁瑣,但不用寫一堆的函數(shù)定義體“{}”,這里只有兩對(duì);容易產(chǎn)生高效的代碼
缺點(diǎn):更改代碼時(shí),代碼改動(dòng)量較大
可以看出,這一管理策略正好與“狀態(tài)管理”的接口語義一致,使人感覺非常輕量。