句柄类 (Thinking in c++__1)
需求:
1)安全技术安全的需要。即使核心实现封闭在库中不可见,但是头文件中的变量定义仍然会曝露一些内部信息;
2)节省编译时间的需要。在开发设计初期,实现部分需要经常变动,连头文件中变量定义也需要经常变动,因此在重编译的时候头文件也需要编译,有时候导致编译时间过长。
方案:
句柄类可解决上述问题:
//:HANDLE.H -- Handle Classes
#ifndef HANDLE_H_
#define HANDLE_H_
class handle {
struct cheshire; // Class declaration only
cheshire* smile;
public:
handle( );
void doit( );~handle( );
};
#endif // HANDLE_H_ 在这种技术中,包含具体实现的结构主体被隐藏在实现文件中。
//:HANDLE.CPP -- Handle implementation
#include "handle.h"
//Define handle's implementation
struct handle:cheshire {
int i;
};
handle::handle() {
smile=(cheshire*)malloc(sizeof(cheshire));
smile->i=0;
}
void handle::doit() {
//do something with i
}
handle::~handle() {
free(smile);
}句柄类的使用就像任何类的使用一样,包括头文件,创建对象,发送信息。但是通过这样的设计,即隐藏了变量的设计,也使得实现作变动时无需重编译头文件。Bruce说虽然这并不是完美的信息隐蔽,但毕竟是一大进步。
浙公网安备 33010602011771号