JavaScript 23 种设计模式之 12 组合模式

JavaScript 23 种设计模式之 12 组合模式

概念与特点

概念:
组合模式又被称为部分 - 整体模式。它是将对象组合成一个树形结构的模式,使用户对单个对象和组合对象具有一致的访问性。

特点:

  1. 客户端可以一致处理单个对象或者组合对象。
  2. 可以很方便在组合内拓展新的对象。
  3. 需要花时间整理类之间的层级关系。
  4. 不容易用继承的方式拓展新功能。

结构与实现

组合模式包含抽象类,树叶类,树枝类。
抽象类:声明树叶类和树枝类的抽象方法。
树叶类:叶节点对象,没有子节点,实现抽象类中的方法。
树枝类:组合中的分支节点对象,有子节点,实现抽象类中的方法。存储和管理子部件,通常包含添加 Add()、移除 Remove()、获取子节点 GetChild() 等方法。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>React App</title>
</head>
<body>
<script>
    class Component{
    
    
        operation(){
    
    

        }
    }
    class Leaf{
    
    
        constructor(name){
    
    
            this.name = name;
        }
        operation(){
    
    
           console.log("树叶"+this.name+"被访问");
        }
    }
    class Composite{
    
    
        constructor(){
    
    
            this.children = [];
        }
        add(c){
    
    
            this.children.push(c);
        }
        remove(c){
    
    
            this.children = this.children.filter((item)=>item!==c);
        }
        getChild(i){
    
    
            return (this.children.splice(i,1)).toString();
        }
        operation(){
    
    
            this.children.map((item)=>{
    
    
                item.operation();
            })
        }
    }
    class Customer{
    
    
        static  main(){
    
    
            let c0 = new Composite();
            let c1 = new Composite();
            let leaf1=new Leaf("1");
            let leaf2=new Leaf("2");
            let leaf3=new Leaf("3");
            c0.add(leaf1);
            c0.add(c1);
            c1.add(leaf2);
            c1.add(leaf3);
            c0.operation();
        }
    }
    Customer.main();
</script>
</body>
</html>

应用场景

  1. 需要表示一个对象的整体与部分结构的场景。
  2. 用户可以用统一的接口使用组合结构中的所有对象。

应用实例

暂无。

总结

组合模式的应用场景主要为:整体与部分之间可以使用层级结构来表现。比如一个公司下面有不同的部门,一个部门下面有总监,总监下面又有经理、主管等。类似于数据结构中的链表结构。这种用法的难点在于构建层级关系。

猜你喜欢

转载自blog.csdn.net/weixin_44135121/article/details/106017465
今日推荐