重构组合模式示例,统一接口定义,增强代码可读性和一致性

This commit is contained in:
2025-12-31 18:33:24 +08:00
parent 86497cc06b
commit 9b51101c27
3 changed files with 92 additions and 73 deletions
+28 -19
View File
@@ -3,16 +3,22 @@
汤宝宝成为了上市集团老总,他们集团有好多好多家分公司...
*/
interface Company {
interface component {
name: string;
children: Company[];
show(prefix: string): void;
add(company: Company): void;
remove(company: Company): void;
getChild(index: number): Company | undefined;
}
class ConcreteCompany implements Company {
class Department implements component {
name: string;
constructor(name: string) {
this.name = name;
}
show(prefix: string): void {
console.log(prefix + this.name);
}
}
class Company implements component {
name: string;
children: Company[] = [];
constructor(name: string) {
@@ -24,18 +30,18 @@ class ConcreteCompany implements Company {
child.show(prefix + "-> ");
}
}
add(company: Company): void {
this.children.push(company);
console.log(`在${this.name}下开设了分公司${company.name}`);
add(company: component): void {
this.children.push(company as Company);
console.log(`在${this.name}下开设了${company.name}`);
}
remove(company: Company): void {
const index = this.children.indexOf(company);
remove(company: component): void {
const index = this.children.indexOf(company as Company);
if (index !== -1) {
this.children.splice(index, 1);
}
console.log(`在${this.name}下关闭了分公司${company.name}`);
console.log(`在${this.name}下裁撤了${company.name}`);
}
getChild(index: number): Company | undefined {
getChild(index: number): component {
return this.children[index];
}
}
@@ -43,12 +49,15 @@ class ConcreteCompany implements Company {
(function () {
console.log("============= 组合模式 =============");
const headOffice = new ConcreteCompany("总公司");
headOffice.add(new ConcreteCompany("汤氏A分公司"));
headOffice.add(new ConcreteCompany("汤氏B分公司"));
headOffice.add(new ConcreteCompany("汤氏C分公司"));
headOffice.getChild(0)?.add(new ConcreteCompany("汤氏A分公司-子公司1"));
headOffice.getChild(0)?.add(new ConcreteCompany("汤氏A分公司-子公司2"));
const headOffice = new Company("总公司");
headOffice.add(new Company("汤氏A分公司"));
headOffice.add(new Department("人事部"));
headOffice.add(new Department("研发部"));
const child = headOffice.getChild(0);
if (child instanceof Company) {
child.add(new Department("市场部"));
child.add(new Department("财务部"));
}
headOffice.remove(headOffice.getChild(2)!);
console.log();