JavaScript Design Patterns for Maintainable Code
Jul 27, 2025 am 04:01 AMThe module mode encapsulates private state through closures, uses IIFE to create independent scopes and exposes limited interfaces, effectively avoiding global pollution and improving testability; 2. The factory mode centralizes object creation logic, returns different types of object instances according to parameters, reducing the client's dependence on specific classes; 3. The observer mode establishes a one-to-many event notification mechanism to decouple publishers and subscribers, and is suitable for event-driven systems; 4. The singleton mode ensures that there is only one instance of a class and provides global access points, which are often used in loggers, configuration management and other scenarios; 5. The decorator mode dynamically adds functions without modifying the original object, supports separation of concerns, and can be used for cross-cutting logic such as performance monitoring, permission verification; the design mode should be selected based on specific requirements: encapsulating the module mode for private data, using factory mode for multiple objects creation, using observer mode for decoupling the event, ensuring that the singleton mode for unique instances, and using decorator mode for dynamic expansion of functions. Reasonable application can improve the clarity, reusability and maintainability of the code structure, but over-design should be avoided.
Writing maintainable JavaScript code is inseparable from understanding and rational application of design patterns. Design patterns are a mature solution to common problems and can improve the structural clarity, reusability and testability of the code. Here are a few JavaScript design patterns that are very practical in actual development to help you write code that is easier to maintain.
1. Module Pattern - encapsulate private state
JavaScript does not have native private
keywords, but private variables and methods can be implemented through closures. Module mode uses Immediate Execution Function (IIFE) to create independent scopes, exposing only necessary interfaces to the outside world.
const UserModule = (function () { let users = []; // private variable function validateName(name) { return name && name.length > 1; } return { add(name) { if (validateName(name)) { users.push(name); console.log(`${name} added.`); } else { console.log("Invalid name"); } }, list() { return [...users]; // Return a copy to avoid external direct modification} }; })();
advantage :
- Hide internal implementation details
- Avoid global variable pollution
- Easy to unit test (through exposed interface)
Tips: Modern ES6 modules (
import
/export
) already support modularity natively, but closure encapsulation is still valuable when private state is required.
2. Factory Pattern - Create a unified entry for objects
When you need to create different types of objects according to conditions, the factory pattern can centrally create logic to avoid duplicate new
operations.
function createUser(type, name) { return { admin: () => ({ role: "admin", name, permissions: ["read", "write", "delete"] }), user: () => ({ role: "user", name, permissions: ["read"] }), guest: () => ({ role: "guest", name, permissions: ["read"] }) }[type] || (() => ({ role: "unknown", name })); } // Use const admin = createUser("admin", "Alice")(); const regularUser = createUser("user", "Bob")();
Applicable scenarios :
- Create objects with similar structures but different behaviors
- Reduce client code's dependence on specific classes
- Configurable object generation (such as form controls, UI components)
3. Observer Pattern—Implement event-driven
Observer pattern is used to implement a one-to-many dependency relationship, and all dependants will be notified when an object's state changes. Very suitable for handling event systems, status updates and other scenarios.
class EventObserver { constructor() { this.observers = new Map(); // key: event, value: array of callbacks } subscribe(event, callback) { if (!this.observers.has(event)) { this.observers.set(event, []); } this.observers.get(event).push(callback); } notify(event, data) { const callbacks = this.observers.get(event); if (callbacks) { callbacks.forEach(cb => cb(data)); } } unsubscribe(event, callback) { const callbacks = this.observers.get(event); if (callbacks) { const index = callbacks.indexOf(callback); if (index > -1) { callbacks.splice(index, 1); } } } } // Use const eventBus = new EventObserver(); eventBus.subscribe("userLogin", user => { console.log("Welcome, " user); }); eventBus.notify("userLogin", "John"); // Output: Welcome, John
Advantages :
- Decouple publishers and subscribers
- Support dynamic binding and unbinding
- Can be used for the prototype of state management (such as the simple version of Vuex)
4. Singleton Pattern – Ensure a unique instance
Some objects only require one instance (such as configuration manager, logger, database connection), and the singleton mode can ensure global uniqueness.
class Logger { constructor() { if (Logger.instance) { return Logger.instance; } this.logs = []; Logger.instance = this; } log(message) { this.logs.push(message); console.log(`[LOG] ${message}`); } getLogCount() { return this.logs.length; } } // Use const logger1 = new Logger(); const logger2 = new Logger(); console.log(logger1 === logger2); // true
Note: The constructor determines whether the instance exists and avoids multiple initializations.
Applicable scenarios :
- Global Configuration Center
- Cache Management
- Routing instance
5. Decorator Pattern—Dynamic expansion function
The decorator mode allows you to dynamically add new functions without modifying the original object. ES2023 supports decorator syntax (requires Babel or TypeScript), but can also be implemented manually.
function withTiming(fn) { return function (...args) { console.log("Starting..."); const start = performance.now(); const result = fn.apply(this, args); const end = performance.now(); console.log(`Execution time: ${end - start} ms`); return result; }; } function fetchData() { // Simulation time-consuming operation for (let i = 0; i < 1e7; i ) {} return "Data fetched"; } const timedFetch = withTiming(fetchData); timedFetch();
use :
- Logs, performance monitoring
- Permission verification
- Enter verification
Summary: How to choose the right design pattern?
- Need to encapsulate private data? → Module Mode
- Multiple object creation logic? → Factory Mode
- Decoupled event notification? → Observer mode
- Globally unique instance? → Singleton Mode
- Dynamic enhancement? → Decorator Mode
These modes are not silver bullets, the key is to understand their intentions and use them in the right scenario. Over-design will increase complexity. Keeping the code simple, clear and readable is the core of maintainability.
Basically all this is not complicated but easy to ignore.
The above is the detailed content of JavaScript Design Patterns for Maintainable Code. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In the Java framework, the difference between design patterns and architectural patterns is that design patterns define abstract solutions to common problems in software design, focusing on the interaction between classes and objects, such as factory patterns. Architectural patterns define the relationship between system structures and modules, focusing on the organization and interaction of system components, such as layered architecture.

TDD is used to write high-quality PHP code. The steps include: writing test cases, describing the expected functionality and making them fail. Write code so that only the test cases pass without excessive optimization or detailed design. After the test cases pass, optimize and refactor the code to improve readability, maintainability, and scalability.

The Guice framework applies a number of design patterns, including: Singleton pattern: ensuring that a class has only one instance through the @Singleton annotation. Factory method pattern: Create a factory method through the @Provides annotation and obtain the object instance during dependency injection. Strategy mode: Encapsulate the algorithm into different strategy classes and specify the specific strategy through the @Named annotation.

The decorator pattern is a structural design pattern that allows dynamic addition of object functionality without modifying the original class. It is implemented through the collaboration of abstract components, concrete components, abstract decorators and concrete decorators, and can flexibly expand class functions to meet changing needs. In this example, milk and mocha decorators are added to Espresso for a total price of $2.29, demonstrating the power of the decorator pattern in dynamically modifying the behavior of objects.

The SpringMVC framework uses the following design patterns: 1. Singleton mode: manages the Spring container; 2. Facade mode: coordinates controller, view and model interaction; 3. Strategy mode: selects a request handler based on the request; 4. Observer mode: publishes and listen for application events. These design patterns enhance the functionality and flexibility of SpringMVC, allowing developers to create efficient and maintainable applications.

The advantages of using design patterns in Java frameworks include: enhanced code readability, maintainability, and scalability. Disadvantages include complexity, performance overhead, and steep learning curve due to overuse. Practical case: Proxy mode is used to lazy load objects. Use design patterns wisely to take advantage of their advantages and minimize their disadvantages.

PHP design patterns provide known solutions to common problems in software development. Common pattern types include creational (such as factory method pattern), structural (such as decorator pattern) and behavioral (such as observer pattern). Design patterns are particularly useful when solving repetitive problems, improving maintainability, and promoting teamwork. In e-commerce systems, the observer pattern can realize automatic updates between shopping cart and order status. Overall, PHP design patterns are an important tool for creating robust, scalable, and maintainable applications.

TDD and design patterns improve code quality and maintainability. TDD ensures test coverage, improves maintainability, and improves code quality. Design patterns assist TDD through principles such as loose coupling and high cohesion, ensuring that tests cover all aspects of application behavior. It also improves maintainability and code quality through reusability, maintainability and more robust code.
