建造者模式用来构建复杂对象的设计模式,指挥者用来提供构造方法,建造者用来提供材料,对象建立时只是一个空架子,也可以用set
方法来自定义构造。
#include <iostream>
#include <vector>
using namespace std;
class Foundation {
public:
virtual ~Foundation() = default;
};
class ThatchedFoundation : public Foundation {
public:
ThatchedFoundation() { cout << "建立了茅草屋地基" << endl; }
};
class Roof {
public:
virtual ~Roof() = default;
};
class ThatchedRoof : public Roof {
public:
ThatchedRoof() { cout << "建立了茅草屋房顶" << endl; }
};
class Window {
};
class Door {
};
class Wall {
public:
Wall(Window *window, Door *door) : window(window), door(door) {}
virtual ~Wall() {
delete(window);
delete(door);
}
private:
Window *window;
Door *door;
};
class ThatchedWall : public Wall {
public:
ThatchedWall(Window *window, Door *door) : Wall(window, door) {
cout << "建立了茅草屋";
if (window)
cout << "有窗的";
if (door)
cout << "有门的";
cout << "的一堵墙" << endl;
}
};
class House {
public:
House() : foundation(nullptr), roof(nullptr) {}
House& setFoundation(Foundation *foundation) {
House::foundation = foundation;
return *this;
}
House& appendWall(Wall *wall) {
walls.push_back(wall);
return *this;
}
House& setRoof(Roof *roof) {
House::roof = roof;
return *this;
}
virtual ~House() {
delete(foundation);
delete(roof);
for (auto wall : walls) {
delete(wall);
}
}
protected:
Foundation *foundation;
vector<Wall*> walls;
Roof *roof;
};
//抽离出建造者
class HouseBuild {
public:
explicit HouseBuild(House& house) : house(house) {}
House& getHouse() {
return house;
}
virtual void buildFoundation() = 0;
virtual void appendWall(Window *window, Door *door) = 0;
virtual void buildRoof() = 0;
protected:
House &house;
};
class ThatchedHouse : public House {
};
class ThatchedHouseBuild : public HouseBuild {
public:
explicit ThatchedHouseBuild(House &house) : HouseBuild(house) {}
void buildFoundation() override {
house.setFoundation(new ThatchedFoundation);
}
void appendWall(Window *window, Door *door) override {
house.appendWall(new ThatchedWall(window, door));
}
void buildRoof() override {
house.setRoof(new Roof);
}
};
class ThatchedHouseDirector {
public:
explicit ThatchedHouseDirector(HouseBuild& build) : build(build) {}
void makeHouse() {
build.buildFoundation();
build.appendWall(new Window, nullptr);
build.appendWall(new Window, nullptr);
build.appendWall(new Window, nullptr);
build.appendWall(nullptr, new Door);
build.buildRoof();
}
private:
HouseBuild& build;
};
int main()
{
//自己盖房子,任意图纸
ThatchedHouse &&thatchedHouse = dynamic_cast<ThatchedHouse&&>(
ThatchedHouse().setFoundation(new ThatchedFoundation)
.appendWall(new ThatchedWall(new Window, nullptr))
.appendWall(new ThatchedWall(new Window, nullptr))
.appendWall(new ThatchedWall(nullptr, new Door))
.appendWall(new ThatchedWall(nullptr, new Door))
.setRoof(new ThatchedRoof));
//施工队使用默认图纸
//House提供房子,Build提供材料,Director提供图纸。
ThatchedHouse thatchedHouse1; //空白的房子
ThatchedHouseBuild thatchedHouseBuild(thatchedHouse1); //将房子交给施工队
ThatchedHouseDirector director(thatchedHouseBuild); //施工队听从指挥者安排
director.makeHouse();
return 0;
}