好的软件工程有两个基本原则,一是接口与实现的分离,二是隐藏实现细节。为此,我们向用户提供头文件,而实现在一个 cpp 文件中。但是,用户提供的头文件中,还是有些 private,虽然用户不能访问,但还是把私有信息暴露给了客户。通过向客户提供只知道类的 public 接口的代理类,就可以使客户能够使用类的服务,而无法访问类的实现细节。
首先我们定义一个普通类:
class T
{
public:
T(int v):m_value(v){}
void SetValue(int value)
{
m_value = value;
}
int GetValue() const
{
return m_value;
}
private:
int m_value;
};
然后我们定义一个代理类:
class Delegate
{
public:
Delegate(int v)
:m_t(new T(v)){}
void SetValue(int v)
{
m_t->SetValue(v);
}
int GetValue() const
{
return m_t->GetValue();
}
private:
T* m_t;
};
在主函数中使用:
#include <iostream>
#include <stdlib.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
Delegate d(5);
d.SetValue(20);
std::cout << d.GetValue() <<std::endl;
system("pause");
return 0;
}
输出结果如下: