模块模式好像不是经典的设计模式,但不可避免的每种编程语言都加入了模块的概念。有时候可能用了模块模式但并不知道自己用的是模块模式。
虽然不是经典的设计模式,但是作为JS创建模块的一种模式也是经常被使用。这里对它做一下介绍
啥是模块
模块模式是一种创建型设计模式,它使用闭包来创建私有变量和方法,同时提供公共接口来访问。模块模式是JavaScript中最常用的模式之一,它提供了封装、私有性和组织代码的能力。
函数式模块
// 使用模块模式创建可复用的组合函数 const useCounter = (function() {// 私有变量let count = 0;let listeners = [];// 私有方法function notifyListeners() {listeners.forEach(listener => listener(count));}// 公共接口return {// 获取当前计数 get count() {return count;},// 增加计数increment: function(value = 1) {count += value;notifyListeners();return count;},// 减少计数decrement: function(value = 1) {count -= value;notifyListeners();return count;},// 重置计数reset: function() {count = 0;notifyListeners();return count;},// 设置计数set: function(value) {count = value;notifyListeners();return count;},// 监听变化watch: function(callback) {listeners.push(callback);return function() {const index = listeners.indexOf(callback);if (index > -1) {listeners.splice(index, 1);}};}}; })();// 使用示例 const counter = useCounter; console.log('初始计数:', counter.count);const unsubscribe = counter.watch((newCount) => {console.log('计数变化:', newCount); });counter.increment(5); counter.decrement(2); counter.reset();unsubscribe(); // 取消监听