建造者模式 (Builder Pattern)
模式概述 (Pattern Overview)
建造者模式是一种创建型设计模式,它允许你分步骤创建复杂对象。该模式使你能够使用相同的创建代码生成不同类型和形式的对象。
意图 (Intent)
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
适用场景 (When to Use)
- 当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时
- 当构造过程必须允许被构造的对象有不同的表示时
- 当需要创建的对象有很多参数,且有些参数是可选的时
UML类图 (UML Class Diagram)
经典建造者模式 (Classic Builder Pattern)
链式建造者模式 (Fluent Builder Pattern)
实现方式 (Implementation Approaches)
1. 经典建造者模式 (Classic Builder Pattern)
/**
* 产品类 - 计算机
* Product Class - Computer
*/
public class Computer {
private String cpu;
private String memory;
private String storage;
private String graphicsCard;
private String motherboard;
private String powerSupply;
private String caseType;
// 私有构造函数,只能通过Builder创建
private Computer(Builder builder) {
this.cpu = builder.cpu;
this.memory = builder.memory;
this.storage = builder.storage;
this.graphicsCard = builder.graphicsCard;
this.motherboard = builder.motherboard;
this.powerSupply = builder.powerSupply;
this.caseType = builder.caseType;
}
@Override
public String toString() {
return "Computer{" +
"cpu='" + cpu + '\'' +
", memory='" + memory + '\'' +
", storage='" + storage + '\'' +
", graphicsCard='" + graphicsCard + '\'' +
", motherboard='" + motherboard + '\'' +
", powerSupply='" + powerSupply + '\'' +
", caseType='" + caseType + '\'' +
'}';
}
/**
* 建造者类
* Builder Class
*/
public static class Builder {
private String cpu;
private String memory;
private String storage;
private String graphicsCard;
private String motherboard;
private String powerSupply;
private String caseType;
public Builder(String cpu, String memory) {
this.cpu = cpu;
this.memory = memory;
}
public Builder storage(String storage) {
this.storage = storage;
return this;
}
public Builder graphicsCard(String graphicsCard) {
this.graphicsCard = graphicsCard;
return this;
}
public Builder motherboard(String motherboard) {
this.motherboard = motherboard;
return this;
}
public Builder powerSupply(String powerSupply) {
this.powerSupply = powerSupply;
return this;
}
public Builder caseType(String caseType) {
this.caseType = caseType;
return this;
}
public Computer build() {
return new Computer(this);
}
}
}
/**
* 客户端代码
* Client Code
*/
public class ClassicBuilderClient {
public static void main(String[] args) {
// 使用建造者模式创建复杂对象
Computer gamingComputer = new Computer.Builder("Intel i9", "32GB DDR4")
.storage("1TB NVMe SSD")
.graphicsCard("NVIDIA RTX 3080")
.motherboard("ASUS ROG Strix")
.powerSupply("750W 80+ Gold")
.caseType("Full Tower RGB")
.build();
System.out.println("游戏电脑配置: " + gamingComputer);
// 创建办公电脑(配置不同)
Computer officeComputer = new Computer.Builder("Intel i5", "16GB DDR4")
.storage("512GB SSD")
.motherboard("MSI B460")
.powerSupply("450W 80+ Bronze")
.caseType("Mini Tower")
.build();
System.out.println("办公电脑配置: " + officeComputer);
}
}
2. 链式建造者模式 (Fluent Builder Pattern)
/**
* 产品类 - HTTP请求
* Product Class - HTTP Request
*/
public class HttpRequest {
private final String method;
private final String url;
private final Map<String, String> headers;
private final Map<String, String> parameters;
private final String body;
private final int timeout;
private final boolean followRedirects;
private HttpRequest(Builder builder) {
this.method = builder.method;
this.url = builder.url;
this.headers = Collections.unmodifiableMap(builder.headers);
this.parameters = Collections.unmodifiableMap(builder.parameters);
this.body = builder.body;
this.timeout = builder.timeout;
this.followRedirects = builder.followRedirects;
}
public void send() {
System.out.println("发送HTTP请求:");
System.out.println("方法: " + method);
System.out.println("URL: " + url);
System.out.println("Headers: " + headers);
System.out.println("Parameters: " + parameters);
System.out.println("Body: " + body);
System.out.println("Timeout: " + timeout + "ms");
System.out.println("Follow Redirects: " + followRedirects);
// 实际的HTTP请求发送逻辑
}
/**
* 链式建造者
* Fluent Builder
*/
public static class Builder {
private String method = "GET";
private String url;
private Map<String, String> headers = new HashMap<>();
private Map<String, String> parameters = new HashMap<>();
private String body = "";
private int timeout = 5000; // 默认5秒
private boolean followRedirects = true;
public Builder(String url) {
this.url = url;
}
public Builder method(String method) {
this.method = method;
return this;
}
public Builder header(String key, String value) {
this.headers.put(key, value);
return this;
}
public Builder parameter(String key, String value) {
this.parameters.put(key, value);
return this;
}
public Builder body(String body) {
this.body = body;
return this;
}
public Builder timeout(int timeout) {
this.timeout = timeout;
return this;
}
public Builder followRedirects(boolean followRedirects) {
this.followRedirects = followRedirects;
return this;
}
public HttpRequest build() {
return new HttpRequest(this);
}
}
}
/**
* 客户端代码
* Client Code
*/
public class FluentBuilderClient {
public static void main(String[] args) {
// 使用链式建造者创建HTTP请求
HttpRequest getRequest = new HttpRequest.Builder("https://api.example.com/users")
.method("GET")
.header("Accept", "application/json")
.header("Authorization", "Bearer token123")
.parameter("page", "1")
.parameter("limit", "10")
.timeout(3000)
.build();
getRequest.send();
System.out.println("\n--- 创建POST请求 ---\n");
// 创建POST请求
HttpRequest postRequest = new HttpRequest.Builder("https://api.example.com/users")
.method("POST")
.header("Content-Type", "application/json")
.header("Authorization", "Bearer token123")
.body("{\"name\": \"John Doe\", \"email\": \"john@example.com\"}")
.timeout(10000)
.followRedirects(false)
.build();
postRequest.send();
}
}
3. 导演者模式 (Director Pattern)
/**
* 产品类 - 文档
* Product Class - Document
*/
public class Document {
private String title;
private String author;
private String content;
private List<String> chapters;
private Map<String, String> metadata;
private Document(Builder builder) {
this.title = builder.title;
this.author = builder.author;
this.content = builder.content;
this.chapters = new ArrayList<>(builder.chapters);
this.metadata = new HashMap<>(builder.metadata);
}
@Override
public String toString() {
return "Document{" +
"title='" + title + '\'' +
", author='" + author + '\'' +
", content='" + content + '\'' +
", chapters=" + chapters +
", metadata=" + metadata +
'}';
}
public static class Builder {
private String title;
private String author;
private String content;
private List<String> chapters = new ArrayList<>();
private Map<String, String> metadata = new HashMap<>();
public Builder title(String title) {
this.title = title;
return this;
}
public Builder author(String author) {
this.author = author;
return this;
}
public Builder content(String content) {
this.content = content;
return this;
}
public Builder addChapter(String chapter) {
this.chapters.add(chapter);
return this;
}
public Builder addMetadata(String key, String value) {
this.metadata.put(key, value);
return this;
}
public Document build() {
return new Document(this);
}
}
}
/**
* 导演者类 - 文档构建导演
* Director Class - Document Builder Director
*/
public class DocumentDirector {
private Document.Builder builder;
public DocumentDirector(Document.Builder builder) {
this.builder = builder;
}
/**
* 构建报告文档
* Build Report Document
*/
public Document buildReport(String title, String author, String summary) {
return builder
.title(title)
.author(author)
.content(summary)
.addChapter("Executive Summary")
.addChapter("Introduction")
.addChapter("Methodology")
.addChapter("Results")
.addChapter("Conclusion")
.addMetadata("type", "report")
.addMetadata("category", "business")
.build();
}
/**
* 构建简历文档
* Build Resume Document
*/
public Document buildResume(String name, String email, String phone) {
return builder
.title(name + " - Resume")
.author(name)
.content("Professional resume")
.addChapter("Personal Information")
.addChapter("Education")
.addChapter("Work Experience")
.addChapter("Skills")
.addChapter("References")
.addMetadata("type", "resume")
.addMetadata("category", "personal")
.build();
}
/**
* 构建技术文档
* Build Technical Document
*/
public Document buildTechnicalDoc(String title, String author, String overview) {
return builder
.title(title)
.author(author)
.content(overview)
.addChapter("Introduction")
.addChapter("Architecture")
.addChapter("Installation")
.addChapter("Configuration")
.addChapter("Usage")
.addChapter("API Reference")
.addChapter("Examples")
.addMetadata("type", "technical")
.addMetadata("category", "documentation")
.build();
}
}
/**
* 客户端代码
* Client Code
*/
public class DirectorClient {
public static void main(String[] args) {
Document.Builder builder = new Document.Builder();
DocumentDirector director = new DocumentDirector(builder);
// 构建报告
Document report = director.buildReport(
"2024年度财务报告",
"财务部门",
"本报告总结了2024年度的财务状况和业绩表现"
);
System.out.println("报告文档: " + report);
System.out.println("\n--- 构建简历 ---\n");
// 构建简历
Document resume = director.buildResume(
"张三",
"zhangsan@example.com",
"138-0000-0000"
);
System.out.println("简历文档: " + resume);
System.out.println("\n--- 构建技术文档 ---\n");
// 构建技术文档
Document techDoc = director.buildTechnicalDoc(
"Spring Boot开发指南",
"技术团队",
"本指南介绍如何使用Spring Boot构建现代Web应用"
);
System.out.println("技术文档: " + techDoc);
}
}
知名框架案例 (Framework Examples)
1. Spring Framework - UriComponentsBuilder
/**
* Spring UriComponentsBuilder的建造者模式
* Builder Pattern of UriComponentsBuilder in Spring
*/
@RestController
@RequestMapping("/builder")
public class SpringBuilderExample {
@GetMapping("/uri")
public ResponseEntity<String> buildUri() {
// 使用UriComponentsBuilder构建URI
UriComponents uriComponents = UriComponentsBuilder.newInstance()
.scheme("https")
.host("api.example.com")
.path("/users/{id}")
.queryParam("name", "John")
.queryParam("age", "25")
.fragment("section1")
.buildAndExpand("123");
String uri = uriComponents.toUriString();
System.out.println("构建的URI: " + uri);
return ResponseEntity.ok("构建的URI: " + uri);
}
@GetMapping("/response")
public ResponseEntity<Map<String, Object>> buildResponse() {
// 使用ResponseEntity.BodyBuilder构建响应
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", Arrays.asList("item1", "item2", "item3"));
response.put("timestamp", System.currentTimeMillis());
return ResponseEntity
.status(HttpStatus.OK)
.header("Custom-Header", "value")
.header("X-Response-Time", String.valueOf(System.currentTimeMillis()))
.contentType(MediaType.APPLICATION_JSON)
.body(response);
}
/**
* 自定义建造者模式
* Custom Builder Pattern
*/
@Component
public static class UserDTOBuilder {
private Long id;
private String username;
private String email;
private String phone;
private List<String> roles;
private Map<String, Object> metadata;
public UserDTOBuilder id(Long id) {
this.id = id;
return this;
}
public UserDTOBuilder username(String username) {
this.username = username;
return this;
}
public UserDTOBuilder email(String email) {
this.email = email;
return this;
}
public UserDTOBuilder phone(String phone) {
this.phone = phone;
return this;
}
public UserDTOBuilder roles(List<String> roles) {
this.roles = roles;
return this;
}
public UserDTOBuilder metadata(Map<String, Object> metadata) {
this.metadata = metadata;
return this;
}
public UserDTO build() {
UserDTO dto = new UserDTO();
dto.setId(id);
dto.setUsername(username);
dto.setEmail(email);
dto.setPhone(phone);
dto.setRoles(roles);
dto.setMetadata(metadata);
return dto;
}
}
@Data
public static class UserDTO {
private Long id;
private String username;
private String email;
private String phone;
private List<String> roles;
private Map<String, Object> metadata;
}
}
2. Netty - Bootstrap
/**
* Netty中Bootstrap的建造者模式
* Builder Pattern of Bootstrap in Netty
*/
public class NettyBuilderExample {
public static void main(String[] args) {
// ServerBootstrap建造者
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(new NioEventLoopGroup(1), new NioEventLoopGroup(8))
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childOption(ChannelOption.TCP_NODELAY, true)
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LoggingHandler(LogLevel.INFO));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new SimpleChannelInboundHandler<String>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
System.out.println("收到消息: " + msg);
ctx.writeAndFlush("服务器响应: " + msg);
}
});
}
});
// 绑定端口
serverBootstrap.bind(8080).addListener(future -> {
if (future.isSuccess()) {
System.out.println("服务器启动成功");
} else {
System.err.println("服务器启动失败");
}
});
}
/**
* 自定义ChannelOption建造者
* Custom ChannelOption Builder
*/
public static class ChannelOptionsBuilder {
private Map<ChannelOption<?>, Object> options = new HashMap<>();
public ChannelOptionsBuilder option(ChannelOption<?> option, Object value) {
options.put(option, value);
return this;
}
public ChannelOptionsBuilder soBacklog(int backlog) {
return option(ChannelOption.SO_BACKLOG, backlog);
}
public ChannelOptionsBuilder soKeepalive(boolean keepalive) {
return option(ChannelOption.SO_KEEPALIVE, keepalive);
}
public ChannelOptionsBuilder tcpNodelay(boolean nodelay) {
return option(ChannelOption.TCP_NODELAY, nodelay);
}
public Map<ChannelOption<?>, Object> build() {
return Collections.unmodifiableMap(options);
}
}
}
3. MyBatis - Configuration
/**
* MyBatis中Configuration的建造者模式
* Builder Pattern of Configuration in MyBatis
*/
public class MyBatisBuilderExample {
/**
* 使用Configuration构建器
* Use Configuration Builder
*/
public static Configuration buildConfiguration() {
// Configuration建造者
Configuration configuration = new Configuration();
// 设置各种配置项
configuration.setCacheEnabled(true);
configuration.setLazyLoadingEnabled(true);
configuration.setMultipleResultSetsEnabled(true);
configuration.setUseColumnLabel(true);
configuration.setUseGeneratedKeys(true);
configuration.setAutoMappingBehavior(AutoMappingBehavior.PARTIAL);
configuration.setDefaultExecutorType(ExecutorType.REUSE);
configuration.setDefaultStatementTimeout(25000);
configuration.setMapUnderscoreToCamelCase(true);
// 添加类型别名
configuration.getTypeAliasRegistry().registerAlias("User", User.class);
configuration.getTypeAliasRegistry().registerAlias("Order", Order.class);
// 添加映射器
configuration.addMapper(UserMapper.class);
configuration.addMapper(OrderMapper.class);
return configuration;
}
/**
* 使用XMLConfigBuilder构建配置
* Build Configuration using XMLConfigBuilder
*/
public static Configuration buildFromXML() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// XMLConfigBuilder是建造者
XMLConfigBuilder builder = new XMLConfigBuilder(inputStream);
return builder.parse();
}
/**
* 使用XMLMapperBuilder构建映射器
* Build Mapper using XMLMapperBuilder
*/
public static void buildMapper(Configuration configuration) throws IOException {
String resource = "UserMapper.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// XMLMapperBuilder是建造者
XMLMapperBuilder mapperBuilder = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
mapperBuilder.parse();
}
/**
* 自定义SQL建造者
* Custom SQL Builder
*/
public static class SqlBuilder {
private StringBuilder sql = new StringBuilder();
public SqlBuilder SELECT(String columns) {
sql.append("SELECT ").append(columns);
return this;
}
public SqlBuilder FROM(String table) {
sql.append(" FROM ").append(table);
return this;
}
public SqlBuilder WHERE(String condition) {
sql.append(" WHERE ").append(condition);
return this;
}
public SqlBuilder AND(String condition) {
sql.append(" AND ").append(condition);
return this;
}
public SqlBuilder OR(String condition) {
sql.append(" OR ").append(condition);
return this;
}
public SqlBuilder ORDER_BY(String column) {
sql.append(" ORDER BY ").append(column);
return this;
}
public String build() {
return sql.toString();
}
}
}
4. Logback - LoggerContextBuilder
/**
* Logback中LoggerContext配置的建造者模式
* Builder Pattern of LoggerContext Configuration in Logback
*/
public class LogbackContextBuilderExample {
public static void main(String[] args) {
// 创建LoggerContext
LoggerContext context = new LoggerContext();
// 使用建造者模式配置LoggerContext
configureLoggerContext(context);
// 使用配置好的Logger
Logger logger = context.getLogger(LogbackContextBuilderExample.class);
logger.info("使用建造者配置的Logger记录日志");
}
/**
* 使用建造者模式配置LoggerContext
* Configure LoggerContext using Builder Pattern
*/
private static void configureLoggerContext(LoggerContext context) {
// 创建控制台appender
ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();
consoleAppender.setContext(context);
consoleAppender.setName("CONSOLE");
// 配置encoder
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setContext(context);
encoder.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
encoder.start();
consoleAppender.setEncoder(encoder);
consoleAppender.start();
// 创建文件appender
FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
fileAppender.setContext(context);
fileAppender.setName("FILE");
fileAppender.setFile("application.log");
PatternLayoutEncoder fileEncoder = new PatternLayoutEncoder();
fileEncoder.setContext(context);
fileEncoder.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
fileEncoder.start();
fileAppender.setEncoder(fileEncoder);
fileAppender.start();
// 获取根logger并配置
Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
rootLogger.setLevel(Level.DEBUG);
rootLogger.addAppender(consoleAppender);
rootLogger.addAppender(fileAppender);
// 创建自定义logger
Logger customLogger = context.getLogger("com.example.custom");
customLogger.setLevel(Level.INFO);
customLogger.setAdditive(false);
customLogger.addAppender(consoleAppender);
}
}
5. Hibernate - Configuration
/**
* Hibernate中Configuration的建造者模式
* Builder Pattern of Configuration in Hibernate
*/
public class HibernateConfigurationBuilderExample {
/**
* 使用Configuration建造者模式
* Use Configuration Builder Pattern
*/
public static Configuration buildConfiguration() {
// Configuration建造者
Configuration configuration = new Configuration();
// 设置数据库连接属性
configuration.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/test");
configuration.setProperty("hibernate.connection.username", "root");
configuration.setProperty("hibernate.connection.password", "password");
// 设置Hibernate属性
configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
configuration.setProperty("hibernate.show_sql", "true");
configuration.setProperty("hibernate.format_sql", "true");
configuration.setProperty("hibernate.hbm2ddl.auto", "update");
configuration.setProperty("hibernate.cache.use_second_level_cache", "true");
configuration.setProperty("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
// 添加实体类
configuration.addAnnotatedClass(User.class);
configuration.addAnnotatedClass(Order.class);
configuration.addAnnotatedClass(Product.class);
// 添加映射文件
try {
configuration.addResource("User.hbm.xml");
configuration.addResource("Order.hbm.xml");
} catch (MappingException e) {
e.printStackTrace();
}
return configuration;
}
/**
* 使用ServiceRegistryBuilder构建服务注册表
* Build Service Registry using ServiceRegistryBuilder
*/
public static ServiceRegistry buildServiceRegistry() {
// ServiceRegistryBuilder是建造者
ServiceRegistryBuilder builder = new ServiceRegistryBuilder();
// 配置各种服务
builder.applySetting("connection.driver_class", "com.mysql.cj.jdbc.Driver");
builder.applySetting("connection.url", "jdbc:mysql://localhost:3306/test");
builder.applySetting("connection.username", "root");
builder.applySetting("connection.password", "password");
builder.applySetting("dialect", "org.hibernate.dialect.MySQLDialect");
// 添加服务
builder.addService(ConnectionProviderInitiator.INSTANCE);
builder.addService(TransactionFactoryInitiator.INSTANCE);
builder.addService(JtaPlatformInitiator.INSTANCE);
return builder.buildServiceRegistry();
}
/**
* 自定义SessionFactory建造者
* Custom SessionFactory Builder
*/
public static class SessionFactoryBuilder {
private final Configuration configuration;
private ServiceRegistry serviceRegistry;
public SessionFactoryBuilder(Configuration configuration) {
this.configuration = configuration;
}
public SessionFactoryBuilder withServiceRegistry(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
return this;
}
public SessionFactoryBuilder withInterceptor(Interceptor interceptor) {
configuration.setInterceptor(interceptor);
return this;
}
public SessionFactoryBuilder withCacheRegionFactory(CacheRegionFactory cacheRegionFactory) {
configuration.setCacheRegionFactory(cacheRegionFactory);
return this;
}
public SessionFactory build() {
if (serviceRegistry != null) {
return configuration.buildSessionFactory(serviceRegistry);
} else {
return configuration.buildSessionFactory();
}
}
}
}
优缺点分析 (Pros and Cons Analysis)
优点 (Advantages)
- 分步构建:可以分步骤构建复杂对象
- 更好的控制:对构建过程有更精细的控制
- 不可变对象:可以创建不可变对象
- 可读性:代码可读性更好,特别是链式调用
- 灵活性:相同的构建过程可以创建不同的表示
缺点 (Disadvantages)
- 代码重复:需要创建重复的建造者代码
- 复杂性:增加了系统的复杂性
- 类的数量:需要创建更多的类
- 性能开销:有一定的性能开销
使用场景 (Use Cases)
适用场景
- 创建复杂对象,有很多可选参数
- 需要创建不可变对象
- 对象的创建过程需要分步骤进行
- 需要避免构造函数参数过多的情况
不适用场景
- 对象很简单,只有几个参数
- 对象的创建过程不需要分步骤
- 性能要求极高的场景
与其他模式的关系 (Relationship with Other Patterns)
与工厂模式的关系
- 工厂模式:关注创建什么产品
- 建造者模式:关注如何创建产品
与组合模式的关系
- 建造者模式可以用来构建组合模式中的复杂对象结构
与单例模式的关系
- 建造者模式可以用来创建复杂的单例对象
最佳实践 (Best Practices)
- 使用不可变对象:建造者模式非常适合创建不可变对象
- 验证参数:在build()方法中验证参数的有效性
- 提供默认值:为可选参数提供合理的默认值
- 考虑性能:在性能敏感的场景下要谨慎使用
- 保持简单:不要让建造者本身变得过于复杂
总结 (Summary)
建造者模式是一种强大的创建型设计模式,特别适合创建复杂对象。它通过将构建过程分解为多个步骤,使得相同的构建过程可以创建不同的表示。在现代Java开发中,链式建造者模式被广泛应用,特别是在配置对象、HTTP请求、数据库查询等场景中。
在Spring、Netty、MyBatis等知名框架中,建造者模式被用于创建复杂的配置对象和请求对象。理解建造者模式的实现原理和适用场景,对于编写灵活、可维护的Java应用程序至关重要。正确使用建造者模式可以大大提高代码的可读性和可维护性。
577



被折叠的 条评论
为什么被折叠?



