重构享元模式示例,统一服装接口类型,增强代码一致性和可读性

This commit is contained in:
2026-01-02 17:26:52 +08:00
parent 4589debb92
commit 232b926a97
3 changed files with 33 additions and 16 deletions
+10 -5
View File
@@ -3,8 +3,13 @@
汤宝宝开了一家服装租赁店,好多客人来店里租衣服~
*/
// 享元抽象类 - 服装接口
interface ClothingInterface {
show(): void;
}
// 享元对象 - 服装
class Clothing {
class Clothing implements ClothingInterface {
private style: string;
private size: string;
private color: string;
@@ -24,13 +29,13 @@ class Clothing {
// 享元工厂 - 服装店
class ClothingFactory {
private clothingPool: { [key: string]: Clothing };
private clothingPool: { [key: string]: ClothingInterface };
constructor() {
this.clothingPool = {};
}
getClothing(style: string, size: string, color: string): Clothing {
getClothing(style: string, size: string, color: string): ClothingInterface {
const key = `${style}-${size}-${color}`;
if (!this.clothingPool[key]) {
this.clothingPool[key] = new Clothing(style, size, color);
@@ -50,14 +55,14 @@ class ClothingFactory {
// 客人
class Customer {
private name: string;
clothing: Clothing[];
clothing: ClothingInterface[];
constructor(name: string) {
this.name = name;
this.clothing = [];
}
rentClothing(clothing: Clothing) {
rentClothing(clothing: ClothingInterface) {
console.log(`${this.name} 租了一件服装.`);
this.clothing.push(clothing);
clothing.show();