// 对象的存储 // this 指针与链式编程(构造器模式) #include #include #include using namespace std; class A { private: int a, b, c; public: void setA(int a) { this->a = a; } void setB(int b) { this->b = b; } void setC(int c) { this->c = c; } void show() { cout << "a = " << a << ", b = " << b << ", c = " << c << endl; } }; class ABuilder { private: A *instance; public: ABuilder() { instance = new A(); } ~ABuilder() { if (instance != NULL) { cout << "~ABuilder()" << endl; delete instance; } } public: ABuilder &a(int a) { instance->setA(a); return *this; } ABuilder &b(int b) { instance->setB(b); return *this; } ABuilder &c(int c) { instance->setC(c); return *this; } A *build() { return instance; } }; int main() { // 构建器设计模式: 构造产品,需要构造器一步一步的完成构造,最后 build() 出产品 ABuilder builder; A *a1 = builder.a(1).b(3).c(8).build(); a1->show(); return 0; }