我記得在閱讀複雜對象配置的情況下閱讀了一段C++的構造函數習語。它特別有用,因爲它有助於爲一些令人討厭的概念啓用RAII,這些概念有太多(通常是衝突)選項的方式。對象構造函數「設置」習慣用法
這是一個簡單的例子。假設你要爲Win32 API窗口編寫一個包裝類。要初始化窗口,您需要知道窗口樣式,擴展窗口樣式,初始窗口位置,初始窗口大小等。在窗口樣式中,許多選項衝突並且不能設置在一起。將所有這些方法放在Window
類中是禁止的,並且阻止定義適當的類不變量。使用臨時對象對所有參數值進行分組可能有助於防止不可能的配置,併爲Window
類定義好的不變量(例如,它始終保存有效的窗口句柄)。
class Settings
{
::DWORD myBasicStyles; // takes lots of different flags.
::DWORD myExtentedStyles; // even more flags.
::POINT myInitialLocation;
::SIZE myInitialSize;
// lots more...
public:
void setInitialPosition (int x, int y);
void setInitialSize (int top, int left);
void useSpecialBorder();
// lots more...
void enableTransparency();
// lots more...
};
class Window
{
::HWND handle;
public:
// map settings unto the horrible list of many parameters expected
// by "CreateWindowEx()", then invoke it to allocate the resource.
Window (const Settings& settings);
};
// calling code.
int main()
{
Settings settings;
settings.setInitialPosition(0, 0);
settings.setInitialSize(500, 300);
settings.setInitiallyVisible(true);
Window window(settings);
// ... rest of application ...
}
但是,我找不到我讀這個的頁面,甚至找不到它的名稱。任何人都可以告訴我這是什麼,並可能鏈接到一個關於這個問題的好資源?
我不知道這有一個名字。 –
@AlexandreC。這不是我經常見到的名字。我只是在和同事討論這種模式,並不記得我聽到的那種叫做什麼。我想爲它命名。 –
順便說一句,如何在一個世界中,你能夠在const對象上調用那些setter? –