JavaScript设计模式-桥接模式(14)

101 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第23天,点击查看活动详情

桥接设计模式是一种偏向于组合的设计模式,而非继承的设计模式,实现的细节从一个模块推送给另一个具有单独模块的对象

桥接设计模式在开发中常用于事件监控,还有数组的一些方法都能够体现出来桥接设计模式的思想,例如数组方法的forEach方法

桥接设计模式在工作中的使用

有一个很多页面的网站,我们预期是让用户可以选择修改网站的主体,如果给每个页面都创建一个主题页面的副本,这样做会很麻烦,这个时候我们就可以使用桥接设计模式进行实现,进行控制网站的主题颜色,通过创建单独的主题根据用户的选择进行加载,接下来我们来实现一下

先声明俩个主题模块类,一个是外观主题,一个是内容主题,里面拥有一个方法,该方法可以进行设置主题颜色

// 外观主题
        class Large {
            constructor(theme) {
                // 主题颜色
                this.theme = theme;
            }
            // 设置主题颜色
            setThemeColor() {
            console.log("Large主题颜色设置为" + this.theme.getColor());
            }
        }

        // 内容主题
        class Small {
            constructor(theme) {
                // 主题颜色
                this.theme = theme;
            }
            // 设置主题颜色
            setThemeColor() {
 console.log("Small主题颜色设置为" + this.theme.getColor());
            }
        }

在声明几个主题颜色类,类里面有一个方法可以获取当前主题颜色

       class RedTheme {
            getColor() {
               return "red";
            }
        }
        class BlueTheme {
            getColor() {
                return "blue";
            }
        }
        class YellowTheme {
            getColor() {
                return "yellow";
            }
        }

我们进行创建主题模块类,在把主题颜色类传递过去调用主题模块设置主题颜色的方法

      // 创建主题颜色
        const RedTheme = new RedTheme();
        const BlueTheme = new BlueTheme();
        const YellowTheme = new YellowTheme();
        // 主题模块
     
     const Large = new Large(RedTheme);
        const Small = new Small(BlueTheme);
        // 设置外观主题和内容主题
        Large.setThemeColor()
        Small.setThemeColor()

桥接设计模式的优势在于就算其中某一模块发生变化,也不会影响其他模块的使用,降低了代码的耦合度,同时因桥接设计模式要求两个模块之间没有耦合关系,否则无法完成独立的变化,所以也是比继承方案更好的解决方案,提高了代码的可扩展性,但是因此桥接设计模式也提高了整体代码的复杂程度

坚持努力,无惧未来!