信息隐藏即对用户不需要知道的信息进行封装隐藏起来,只提供必要的方法或接口给用户即可。在面向对象程序设计中,就是这样,用户只要调用方法就可以获得对象的信息,但是不知道对象底层如何创建。
如同生活中汽车、电脑一样,我们通常只知道操控方向盘、键盘来控制,但是并不知道原理是什么,怎么实现。
class Car
{
public:
Car(){}
Car(string carname, double price, int speed, string director) :
carname(carname), price(price), speed(speed), director(director) {
}
void buycar(string director,double price,string carname)
{
cout << director << "花了" << price << "万买下了" << carname << endl;
}
void upspeed(int speed) {
speed++;
}
void downspeed(int speed) {
speed--;
}
int getspeed() {
return this->speed;
}
double getprice() {
return this->price;
}
string getcarname() {
return this->carname;
}
void turnlr(int a) {
if (a > 0) {
cout << "左" << endl;
}
else
{
cout << "右" << endl;
}
}
private:
string carname;
double price;
int speed;
string director;
};
上面就是一个典型的例子。
信息隐藏原理:应该这样设计和确定模块,使得一个模块内包含的信息 (过程和数据)对于不需要这些信息的模块来说,是不能访问的。
局部化是指把一些关系密切的软件元素物理地放得彼此靠近。
如果在测试期间和以后的软件维护期间需要修改软件,使用信息隐藏原理作为模块化系统设计的标准就会带来极大好处。