内容目录
#include <iostream>
#include <string>
// Pizza类
class Pizza {
public:
std::string dough;
std::string sauce;
std::string topping;
void makePizza() {
std::cout << "Making pizza with " << dough << " dough, " << sauce << " sauce and " << topping << " topping." << std::endl;
}
};
// PizzaBuilder接口
class PizzaBuilder {
public:
virtual void buildDough() = 0;
virtual void buildSauce() = 0;
virtual void buildTopping() = 0;
virtual Pizza* getPizza() = 0;
};
// ConcretePizzaBuilder实现
class MargheritaPizzaBuilder : public PizzaBuilder {
private:
Pizza* pizza;
public:
MargheritaPizzaBuilder() {
pizza = new Pizza();
}
void buildDough() override {
pizza->dough = "thin";
}
void buildSauce() override {
pizza->sauce = "tomato";
}
void buildTopping() override {
pizza->topping = "cheese";
}
Pizza* getPizza() override {
return pizza;
}
};
// Director类
class PizzaDirector {
public:
Pizza* makePizza(PizzaBuilder* builder) {
builder->buildDough();
builder->buildSauce();
builder->buildTopping();
return builder->getPizza();
}
};
int main() {
PizzaDirector director;
MargheritaPizzaBuilder builder;
Pizza* pizza = director.makePizza(&builder);
pizza->makePizza();
delete pizza;
return 0;
}
打赏作者