虽然从实施的角度来看,该解决方案很简洁,但从架构上来说,它只完成了一半。 Getter/Setter 模式的要点是让类控制其数据并减少耦合(即其他类知道how数据被存储)。该解决方案实现了前者,但不能完全实现后者。
事实上,另一个类现在必须知道两件事 - 变量的名称和 getter 上的方法(即.get()
) 而不是一个 - 例如getWidth()
。这会导致耦合增加。
话虽如此,这却是众所周知的建筑问题。归根结底,这并不重要。
EDIT好吧,现在废话了,这里是使用运算符的 getter 版本,所以你不必这样做.value
or .get()
template <class T>
struct TemplateParameterIndirection // This hack works for MinGW's GCC 4.4.1, dunno others
{
typedef T Type;
};
template <typename T,class Owner>
class Getter
{
public:
friend TemplateParameterIndirection<Owner>::Type; // Befriends template parameter
operator T()
{
return value;
}
protected:
T value;
T& operator=( T other )
{
value = other;
return value;
}
};
class Window
{
public:
Getter<int,Window> _width;
Getter<int,Window> _height;
void resize(int width,int height)
{
// do actual window resizing logic
_width = width; //using the operator
_height = height; //using the operator
}
};
void someExternalFunction()
{
Window win;
win.resize(640,480); // Ok: public method
int w2 = win._width; //using the operator
//win._height = 480; //KABOOM
}
EDIT修复了硬编码赋值运算符。如果类型本身有赋值运算符,这应该可以很好地工作。默认情况下,结构体具有这些结构,因此对于简单的结构体来说,它应该可以开箱即用。
对于更复杂的类,您将需要实现一个足够公平的赋值运算符。和RVO http://en.wikipedia.org/wiki/Return_value_optimization and 写时复制 http://en.wikipedia.org/wiki/Copy-on-write优化,这在运行时应该相当有效。