生成器模式是一種在TypeScript/JavaScript中非常常見的創建型設計模式,它使你能夠分步驟創建復雜物件,當你需要創建一個可能有許多配置選項的物件時, 該模式會特別有用,
問題
假設我們需要構造一個復雜物件,構造時需要給這個物件的諸多成員變數進行初始化作業,如果使用傳統的建構式創建這個物件,那么它的建構式將十分復雜,比如new Product(partA, partB, partC, ...),這樣的建構式不僅缺乏靈活性還會嚴重的影響代碼的可讀性,因此我們需要一種更優秀的方法來創建復雜物件,
創建想要生成的產品類
class Product {
public partA: string;
public partB: string;
public partC: string;
public partD: string;
}
創建生成器類
可以將基本生成器定義為一個介面,再為每個形式的產品創建具體的生成類,這里只定義一個生成器類作為演示
class ProductBuilder {
private product: Product;
constructor() {
// 創建要生成的物件
this.product = new Product();
}
// 以下為給物件添加各部分的方法
public setPartA(partA: string): this {
this.product.partA = partA;
return this;
}
public setPartB(partB: string): this {
this.product.partB = partB;
return this;
}
public setPartC(partC: string): this {
this.product.partC = partC;
return this;
}
public setPartD(partD: string): this {
this.product.partD = partD;
return this;
}
// 完成產品生成
public build(): void {
// 這里可以寫具體的構建完成后要執行的操作
console.log(this.product);
}
}
測驗代碼
const product = new ProductBuilder()
.setPartA('這是Part A')
.setPartB('這是Part B')
.setPartD('這是Part D')
.build();
// Product { partA: '這是Part A', partB: '這是Part B', partD: '這是Part D' }
const product = new ProductBuilder()
.setPartA('這是Part A')
.setPartB('這是Part B')
.build();
// Product { partA: '這是Part A', partB: '這是Part B' }
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/134980.html
標籤:設計模式
