写一个建造者模式的c++代码实例
时间: 2024-04-29 11:27:11 浏览: 79
c++-设计模式之“建造者模式(Builder)”
好的,这是一个简单的建造者模式的 C 代码实例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Product */
typedef struct {
char part1[20];
char part2[20];
char part3[20];
} Product;
/* Builder interface */
typedef struct {
void (* build_part1)(Product *product);
void (* build_part2)(Product *product);
void (* build_part3)(Product *product);
} Builder;
/* Concrete builder */
typedef struct {
Builder builder; /* Inherit from Builder interface */
Product *product;
} ConcreteBuilder;
void build_part1(Product *product) {
strcpy(product->part1, "Part 1");
}
void build_part2(Product *product) {
strcpy(product->part2, "Part 2");
}
void build_part3(Product *product) {
strcpy(product->part3, "Part 3");
}
void ConcreteBuilder_create(ConcreteBuilder *builder) {
builder->builder.build_part1 = build_part1;
builder->builder.build_part2 = build_part2;
builder->builder.build_part3 = build_part3;
builder->product = malloc(sizeof(Product));
}
void ConcreteBuilder_build(ConcreteBuilder *builder) {
builder->builder.build_part1(builder->product);
builder->builder.build_part2(builder->product);
builder->builder.build_part3(builder->product);
}
Product *ConcreteBuilder_get_result(ConcreteBuilder *builder) {
return builder->product;
}
/* Director */
typedef struct {
void (* construct)(Builder *builder);
} Director;
void construct(Builder *builder) {
builder->build_part1(builder);
builder->build_part2(builder);
builder->build_part3(builder);
}
void Director_construct(Director *director, Builder *builder) {
director->construct(builder);
}
int main() {
ConcreteBuilder builder;
ConcreteBuilder_create(&builder);
Director director = { construct };
Director_construct(&director, &builder.builder);
Product *product = ConcreteBuilder_get_result(&builder);
printf("Product parts: %s, %s, %s\n", product->part1, product->part2, product->part3);
free(product);
return 0;
}
```
这里定义了一个 `Product` 结构体表示产品,具体包含三个部分 `part1`、`part2`、`part3`;同时定义了一个 `Builder` 接口以及一个 `ConcreteBuilder` 具体实现类。在 `ConcreteBuilder` 中实现了 `Builder` 中定义的三种构建方法,分别构建产品中的三个部分。`ConcreteBuilder` 将这三个构建方法包装起来,在调用 `ConcreteBuilder_build` 方法时,一次性将三个部分构建出来。`ConcreteBuilder_get_result` 方法最终返回构建的产品。
在 `Director` 结构体中,定义了一个 `construct` 方法,其接收一个 `Builder` 接口,使得构造产品的过程得以独立出来。在例子中,创建了一个 `ConcreteBuilder`,使用 `Director` 中的 `construct` 方法构建了一个 `Product`,再通过 `get_result` 方法获取构建好的产品,并打印出来。
阅读全文