【设计模式 04】建造者模式
如果要构建的对象很复杂,那么可以将整个构建过程拆分成多个步骤,并为每一个步骤定义一个抽象的接口。并添加一个指导者用来控制构建产品的顺序和步骤。
Java实现:
// 产品类
class Product {
private String part1;
private String part2;
public void setPart1(String part1) {
this.part1 = part1;
}
public void setPar2(String part2) {
this.part2 = part2;
}
// 其他属性和方法
}
// 抽象建造者接口
interface Builder {
void buildPart1(String part1);
void buildPart2(String part2);
Product getResult();
}
// 具体建造者类
class ConcreteBuilder implements Builder {
private Product product = new Product();
@Override
public void buildPart1(String part1) {
product.setPart1(part1);
}
@Override
public void buildPart2(String part2) {
product.setPart2(part2);
}
@Override
public Product getResult() {
return product;
}
}
// 指导者类
class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
// 调用方法构建产品
public void construct() {
builder.buildPart1("Part 1");
builder.buildPart2("Part 2");
}
}
public class Main {
public static void main(String[] args) {
// 创建指导者和建造者对象
Builder builder = new ConcreteBuilder();
Director director = new Director(builder);
// 指导者构建产品
director.construct();
// 获取构建好的产品
Product product = builder.getResult();
// 输出产品信息
System.out.println(product);
}
}
CPP版题解:
#include <iostream>
#include <string>
using namespace std;
class Bike {
public:
string frame;
string tires;
void setFrame(const string& frame) {
this->frame = frame;
}
void setTires(const string& tires) {
this->tires = tires;
}
friend ostream& operator << (ostream& os, const Bike& bike) {
os << bike.frame << " " << bike.tires;
return os;
}
};
class BikeBuilder {
public:
virtual void buildFrame() = 0;
virtual void buildTires() = 0;
virtual Bike getResult() = 0;
};
class MountainBikeBuilder : public BikeBuilder {
private:
Bike bike;
public:
void buildFrame() override {
bike.setFrame("Aluminum Frame");
}
void buildTires() override {
bike.setTires("Knobby Tires");
}
Bike getResult() override {
return bike;
}
};
class RoadBikeBuilder : public BikeBuilder {
private:
Bike bike;
public:
void buildFrame() override {
bike.setFrame("Carbon Frame");
}
void buildTires() override {
bike.setTires("Slim Tires");
}
Bike getResult() override {
return bike;
}
};
class BikeDirector {
public:
Bike construct(BikeBuilder& builder) {
builder.buildFrame();
builder.buildTires();
return builder.getResult();
}
};
int main() {
int N;
cin >> N;
BikeDirector director;
for (int i = 0; i < N; i++) {
string bikeType;
cin >> bikeType;
BikeBuilder* builder;
if (bikeType == "mountain") {
builder = new MountainBikeBuilder();
} else {
builder = new RoadBikeBuilder();
}
Bike bike = director.construct(*builder);
cout << bike << endl;
delete builder;
}
return 0;
}
原文地址:https://blog.csdn.net/weixin_55252589/article/details/136519667
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!