Logo
Section 1 / 19

理解建造者模式

使用可链式调用的流畅 API 逐步构建复杂对象,以确保清晰性和灵活性。

导入

理解建造者模式

使用可链式调用的流畅 API 逐步构建复杂对象,以确保清晰性和灵活性。

代码示例

1new QueryBuilder() 2 .withText('foo') 3 .inCategory('books') 4 .paginate(1, 20) 5 .build()
...
1 / 5

Node.js

1class SearchQueryBuilder { 2 constructor() { 3 this.query = { 4 filters: {}, 5 pagination: {} 6 }; 7 } 8 9 withText(text) { 10 this.query.filters.text = text; 11 return this; 12 } 13 14 inCategory(category) { 15 this.query.filters.category = category; 16 return this; 17 } 18 19 withTags(tags) { 20 this.query.filters.tags = tags; 21 return this; 22 } 23 24 paginate(page, limit) { 25 this.query.pagination = { page, limit }; 26 return this; 27 } 28 29 build() { 30 return this.query; 31 } 32} 33 34// Usage 35const query = new SearchQueryBuilder() 36 .withText('node.js') 37 .inCategory('books') 38 .withTags(['design', 'backend']) 39 .paginate(2, 10) 40 .build(); 41 42console.log(query);

TypeScript

1type Query = { 2 filters: { 3 text?: string; 4 category?: string; 5 tags?: string[]; 6 }; 7 pagination: { 8 page?: number; 9 limit?: number; 10 }; 11}; 12 13class SearchQueryBuilder { 14 private query: Query = { 15 filters: {}, 16 pagination: {} 17 }; 18 19 withText(text: string): this { 20 this.query.filters.text = text; 21 return this; 22 } 23 24 inCategory(category: string): this { 25 this.query.filters.category = category; 26 return this; 27 } 28 29 withTags(tags: string[]): this { 30 this.query.filters.tags = tags; 31 return this; 32 } 33 34 paginate(page: number, limit: number): this { 35 this.query.pagination = { page, limit }; 36 return this; 37 } 38 39 build(): Query { 40 return this.query; 41 } 42} 43 44// Usage 45const query = new SearchQueryBuilder() 46 .withText('node.js') 47 .inCategory('books') 48 .withTags(['design', 'backend']) 49 .paginate(2, 10) 50 .build(); 51 52console.log(query);

工厂模式:动态生成配置驱动的服务

构建一个最小化的电子邮件模板生成器