重构享元模式示例,统一服装接口类型,增强代码一致性和可读性
This commit is contained in:
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user