摘要:将定义和声明分开,并包含声明定义变量。使用句柄类和接口类减少文件依赖。
(cascading compilation dependencies)
class Person {
public:
Person(const std::string& name, const Date& birthday,const Address& addr);
std::string name() const;
std::string birthDate() const;
std::string address() const;
...
private:
std::string theName; // implementation detail
Date theBirthDate; // implementation detail
Address theAddress; // implementation detail
};如果正常的编译Person 需要知道相应类型的定义,需要包含特定的头文件
#include <string>
#include "date.h"
#include "address.h"其主要的目的是,需要确切的知道在Person中相应 string ,date 和 address 类的大小。
最小化编译依赖的本质是:头文件编译时是自满足的,如果不能,那依赖声明而不是定义。
句柄类主要的作用是,减少文件之间的依赖。
#include "Person.h"
// we're implementing the Person class,
// so we must #include its class definition
#include "PersonImpl.h"
// we must also #include PersonImpl's class
// definition, otherwise we couldn't call
// its member functions; note that
// PersonImpl has exactly the same
// member functions as Person — their
// interfaces are identical
Person::Person(const std::string& name, const Date& birthday,
const Address& addr) : pImpl(new PersonImpl(name, birthday, addr)){}
std::string Person::name() const{
return pImpl->name();
}使用虚拟类实现
class Person {
public:
virtual ~Person();
virtual std::string name() const = 0;
virtual std::string birthDate() const = 0;
virtual std::string address() const = 0;
...
};具体的使用方式是:
class Person {
public:
...
static std::tr1::shared_ptr<Person> // return a tr1::shared_ptr to a new
create(const std::string& name, // Person initialized with the
const Date& birthday, // given params; see Item 18 for
const Address& addr); // why a tr1::shared_ptr is returned
...
};客户端使用
std::string name;
Date dateOfBirth;
Address address;
...
// create an object supporting the Person interface
std::tr1::shared_ptr<Person> pp(Person::create(name, dateOfBirth, address));
...
std::cout << pp->name() // use the object via the
<< " was born on " // Person interface
<< pp->birthDate()
<< " and now lives at "
<< pp->address();
... // the object is automatically deleted when pp goes out of scope总结:
1)将声明和实现分开,并成对改变。
2)使用句柄类和接口类,减少依赖。即仅当声明类的接口改变时,才会重新编译。