设计模式之组合模式
组合模式
- 组合模式是以结构化的方式,是单一对象具有树形结构,让单一对象更具有结构性。
组合模式的实例
- 举个栗子,在雇员和雇主之间是都是存在上下级关系的,如何用代码更直观的表达和关系与关系的操作,这是一个棘手的问题。
- 但通过组合模式,将关系表达为树状结构将更方便更直观的表达,如下。
class Employee {
constructor(name, dept, sal) {
this.name = name;
this.dept = dept;
this.salary = sal;
this.subordinates = [];
}
add(employee) {
this.subordinates.push(employee);
}
remove(employee) {
this.subordinates.splice(this.subordinates.indexOf(employee));
}
getSubordinates() {
return this.subordinates;
}
toString() {
return (`Employee :[ Name : ${this.name},dept :${this.dept},salary : ${this.salary}]`)
}
}
- 所以当我们添加雇员和关系的时候将更加方便的添加,而且对于一个雇员,它只需要关心和下属的关系维护,而不需要关系上级和一些间接的关系。
- 这样会更清晰和维护更方便。
const CEO = new Employee('lazy', 'CEO', 30000);
const headSales = new Employee('Robert', 'Head Sales', 20000);
const headMarketing = new Employee('Michel', 'head Marketing', 20000);
const clerk1 = new Employee('Laura', 'Marketing', 10000);
const clerk2 = new Employee('Bob', 'Marketing', 10000);
const salesExecutive1 = new Employee('Rechard', 'Sales', 10000);
const salesExecutive2 = new Employee('Rob', 'Sales', 10000);
CEO.add(headSales);
CEO.add(headMarketing);
headMarketing.add(salesExecutive1);
headMarketing.add(salesExecutive2);
headMarketing.add(clerk1);
headMarketing.add(clerk2);
- 那么我们打印来说也只要打印最高级别的上级就能实现全部打印。
function printAllEmployee(employee) {
for(const subEmployee of employee.getSubordinates()) {
console.log(subEmployee.toString());
if(subEmployee.getSubordinates().length > 0) {
printAllEmployee(subEmployee);
}
}
}
console.log(CEO.toString());
printAllEmployee(CEO);
/*
* index.html:63 Employee :[ Name : lazy,dept :CEO,salary : 30000]
* index.html:56 Employee :[ Name : Robert,dept :Head Sales,salary : 20000]
* index.html:56 Employee :[ Name : Michel,dept :head Marketing,salary : 20000]
* index.html:56 Employee :[ Name : Rechard,dept :Sales,salary : 10000]
* index.html:56 Employee :[ Name : Rob,dept :Sales,salary : 10000]
* index.html:56 Employee :[ Name : Laura,dept :Marketing,salary : 10000]
* index.html:56 Employee :[ Name : Bob,dept :Marketing,salary : 10000]
*/
组合模式的优势
- 让相互关联的对象产生了结构性,无论是在关系修改或者是关系直观上,都只需要关心当前下级的关系,那么这也能更好的降低关系和关系之间的复杂度,加强单对像关系结构的可维护性。
本文来自博客园,作者:懒惰ing,转载请注明原文链接:https://www.cnblogs.com/landuo629/p/14375717.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?