weikee94 / design-patterns

Design Patterns
0 stars 0 forks source link

Module Pattern #3

Open weikee94 opened 11 months ago

weikee94 commented 11 months ago

Concept

The module pattern is an effective method for dividing a larger codebase into smaller, reusable components. It encourages code encapsulation by default, keeping values private within a module and preventing them from being altered. Only the values explicitly marked for export with the "export" keyword can be accessed by other parts of the codebase.

模块模式是将较大的代码文件分割成多个更小、可重用的组件的有效方法。它默认情况下鼓励代码封装,通过将模块内的值保持为私有,防止其被修改。只有使用 "export" 关键字明确标记为导出的值才可以被代码中的其他部分访问。

Tradeoffs

Encapsulation: The values within a module are scoped to that specific module. Values that aren't explicitly exported are not available outside of the module.

Reusability: We can reuse modules throughout our application

Stackblitz

math.js

export function sum(x, y) {
  return x + y;
}
export function multiply(x, y) {
  return x * y;
}
export function subtract(x, y) {
  return x - y;
}
export function divide(x, y) {
  return x / y;
}

index.js

import { sum, subtract, divide, multiply } from './math.js';

console.log('Sum', sum(1, 2));
console.log('Subtract', subtract(1, 2));
console.log('Divide', divide(1, 2));
console.log('Multiply', multiply(1, 2));