typedef struct {
void (*initMemory)();
void (*setClock)();
void (*verifySignature)();
void (*loadKernel)();
void (*bootKernel)();
} BootloaderBuilder;
void buildBootloader(BootloaderBuilder* builder) {
if(builder->initMemory) {
builder->initMemory();
}
if(builder->setClock) {
builder->setClock();
}
if(builder->verifySignature) {
builder->verifySignature();
}
if(builder->loadKernel) {
builder->loadKernel();
}
if(builder->bootKernel) {
builder->bootKernel();
}
}
void initMemoryFunction() {
// Initialize DDR, Cache, MMU
}
void setClockFunction() {
// Initialize PLL and set CPU clock frequency
}
void verifySignatureFunction() {
// Verify the digital signature of the OS image
}
void loadKernelFunction() {
// Load the OS kernel from storage
}
void bootKernelFunction() {
// Transfer control to the OS
}
int main() {
// 初始化 builder,可以自由抽換 init Function
BootloaderBuilder builder = {
.initMemory = initMemoryFunction,
.setClock = setClockFunction,
.verifySignature = verifySignatureFunction,
.loadKernel = loadKernelFunction,
.bootKernel = bootKernelFunction
};
// 呼叫 builder (BootLoader)
buildBootloader(&builder);
}
// Represents a product created by the builder
class Bicycle {
public:
Bicycle(std::string make, std::string model, std::string colour, int height)
: Make(make), Model(model), Colour(colour), Height(height) {}
std::string Make;
std::string Model;
int Height;
std::string Colour;
};
// The builder abstraction
class IBicycleBuilder {
public:
virtual std::unique_ptr<Bicycle> GetResult() = 0;
virtual std::string GetColour() = 0;
virtual void SetColour(std::string colour) = 0;
virtual int GetHeight() = 0;
virtual void SetHeight(int height) = 0;
};
// Concrete builder implementation.
class GTBuilder : public IBicycleBuilder {
public:
std::unique_ptr<Bicycle> GetResult() override {
return Height == 29 ? std::make_unique<Bicycle>("GT", "Avalanche", Colour, Height) : nullptr;
}
std::string GetColour() override { return Colour; }
void SetColour(std::string colour) override { Colour = colour; }
int GetHeight() override { return Height; }
void SetHeight(int height) override { Height = height; }
private:
std::string Colour;
int Height;
};
// The director.
class MountainBikeBuildDirector {
public:
MountainBikeBuildDirector(std::unique_ptr<IBicycleBuilder> builder)
: builder(std::move(builder)) {}
void Construct() {
builder->SetColour("Red");
builder->SetHeight(29);
}
std::unique_ptr<Bicycle> GetResult() {
return builder->GetResult();
}
private:
std::unique_ptr<IBicycleBuilder> builder;
};
// Client code
int main() {
auto director = std::make_unique<MountainBikeBuildDirector>(std::make_unique<GTBuilder>());
director->Construct();
std::unique_ptr<Bicycle> myMountainBike = director->GetResult();
if (myMountainBike) {
std::cout << "Bicycle built with Make: " << myMountainBike->Make << ", Model: " << myMountainBike->Model << std::endl;
} else {
std::cout << "Bicycle could not be built." << std::endl;
}
}