当前位置: 首页 > news >正文

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

模块模式

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

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

闭包:

// 闭包 模块模式
const obj = (function() {let count = 0return {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)

http://www.mrgr.cn/news/8971.html

相关文章:

  • Android笔试面试题AI答之Kotlin(18)
  • postgresql 使用explain 进行SQL分析
  • ios白苹果修复办法有哪些?
  • 【微服务】springboot整合对象映射工具MapStruct使用详解
  • nginx做代理 转发前端请求到后端
  • 698. 划分为k个相等的子集
  • java日常管理
  • 如何使用 vue2+element-ui 处理复杂表单,避免单文件过大的问题
  • Android14 以太网共享功能 相关代码简介
  • Lumos学习王佩丰Excel第十四讲:日期函数
  • Tailwind CSS的介绍和使用
  • (十)Flink Table API 和 SQL 基本概念
  • 数据库的读写分离技术MVCC
  • 线性代数 第二讲 矩阵_逆矩阵_伴随矩阵_分块矩阵_初等矩阵_矩阵的秩
  • c语言利用switch多路开关制作输入月份判断季节的程序
  • Python如何实现PPT演示文稿到图片的批量转换
  • 【AI】阿里云AI开发平台PAI:构建智能未来
  • 每日Attention学习16——Multi-layer Multi-scale Dilated Convolution
  • SQLserver中的增删改查和数据类型
  • Python酷库之旅-第三方库Pandas(098)