实现享元模式示例,添加服装、服装工厂和客户类,增强代码可读性

This commit is contained in:
2026-01-02 01:34:47 +08:00
parent 4f8d653153
commit 4589debb92
3 changed files with 281 additions and 0 deletions
+96
View File
@@ -0,0 +1,96 @@
/*
实例:
汤宝宝开了一家服装租赁店,好多客人来店里租衣服~
*/
// 享元对象 - 服装
class Clothing {
private style: string;
private size: string;
private color: string;
constructor(style: string, size: string, color: string) {
this.style = style;
this.size = size;
this.color = color;
}
show() {
console.log(
`服装款式: ${this.style}, 尺码: ${this.size}, 颜色: ${this.color}`
);
}
}
// 享元工厂 - 服装店
class ClothingFactory {
private clothingPool: { [key: string]: Clothing };
constructor() {
this.clothingPool = {};
}
getClothing(style: string, size: string, color: string): Clothing {
const key = `${style}-${size}-${color}`;
if (!this.clothingPool[key]) {
this.clothingPool[key] = new Clothing(style, size, color);
}
return this.clothingPool[key];
}
showStock() {
console.log("\n服装库存:");
for (const key in this.clothingPool) {
console.log(`Key: ${key} ->`);
this.clothingPool[key].show();
}
}
}
// 客人
class Customer {
private name: string;
clothing: Clothing[];
constructor(name: string) {
this.name = name;
this.clothing = [];
}
rentClothing(clothing: Clothing) {
console.log(`${this.name} 租了一件服装.`);
this.clothing.push(clothing);
clothing.show();
}
showClothing() {
console.log(`\n客人${this.name}租赁的服装有:`);
this.clothing.forEach((c) => c.show());
}
}
(function () {
console.log("============= 享元模式 =============");
const factory = new ClothingFactory();
// 客人1租衣服
const customer1 = new Customer("小红");
customer1.rentClothing(factory.getClothing("连衣裙", "M", "红色"));
customer1.rentClothing(factory.getClothing("牛仔裤", "L", "蓝色"));
// 客人2租衣服
const customer2 = new Customer("小明");
customer2.rentClothing(factory.getClothing("连衣裙", "M", "红色")); // 共享同一件连衣裙
customer2.rentClothing(factory.getClothing("夹克", "XL", "黑色"));
console.log();
// 显示租赁情况
customer1.showClothing();
customer2.showClothing();
// 显示服装库存
factory.showStock();
console.log("\n=========== 享元模式结束 ===========");
})();