通常需要完成以下任务:更改某物的状态,执行操作,然后将状态更改回原始状态。例如,在 Win32 GDI 中,需要更改背景颜色,然后进行一些绘图,然后将颜色更改回来。
它可以直接完成:
COLORREF oldColor = SetBkColor( deviceContext, newColor );
drawStuff( deviceContext );
SetBkColor( deviceContext, oldColor );
或者通过一个括号类,它将在构造函数中进行前向更改和在析构函数中进行后向更改:
CBkColorSwitcher switcher( deviceContext, newColor );
drawStuff( deviceContext );
//once control reaches end of block the switcher is destroyed and the change is reverted
括号类的优点是显而易见的——如果在更改之间引发异常,则更改将正确恢复。有什么缺点?