【设计模式】模块模式和桥接模式

模块模式

模块化模式最初被定义为在传统软件工程中为类提供私有和公共封装的一种方法。

能够使一个单独的对象拥有公共/私有的方法和变量,从而屏蔽来自全局作用域的特殊部分。这可以减少我们的函数名与在页面中其他脚本区域内定义的函数名冲突的可能性。

闭包:

// 闭包 模块模式
const obj = (
    function() {
        let count = 0
        return {
            add: function () {
                count++
                return count
            },
            reduce: function () {
                count--
                return count
            }
        }
    }
)()
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<script src="index.js"></script>
<script>
    console.log(obj)
</script>
</body>
</html>

es6模块化:

let count = 0
function add() {
    count++
    return count
}
function reduce() {
    count--
    return count
}
export default {
    add,
    reduce
}
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<!--<script src="index.js"></script>-->
<script type="module">
    import obj from './index.js'

    console.log(obj)
</script>
</body>
</html>

桥接模式

桥接模式:将抽象部分与它的实现部分分离,使它们都可以独立地变化。
使用场景:一个类存在两个或多个独立变化的维度,且这两个维度都需要进行扩展

  • 优点:
    把抽象与实现隔离开,有助于独立地管理各组成部分。
  • 缺点:
    每使用一个桥接元素都要增加一次函数调用,这对应用程序的性能会有一些负面影响一一提高了系统的复杂程度。

比如,一个 toast ,给一个元素绑定动画效果,可以将动画效果的实现隔离,从而不同的 toast 可以在 与不同的动画相结合。

const Animation = {
    fade: {
        show: function (element) {
            console.log(element, 'fade show');
        },
        hide: function (element) {
            console.log(element, 'fade hide');
        }
    },
    slide: {
        show: function (element) {
            console.log(element, 'slide show');
        },
        hide: function (element) {
            console.log(element, 'slide hide');
        }
    }
}

function Toast(element, animation) {
    this.element = element;
    this.animation = animation;
}

Toast.prototype.show = function () {
    this.animation.show(this.element);
}
Toast.prototype.hide = function () {
    this.animation.hide(this.element);
}

const toast = new Toast('div', Animation.fade);
toast.show();
setTimeout(() => {
    toast.hide();
}, 1000)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秀秀_heo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值