亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
2. Observer Pattern – Handle Events and State Changes
3. Factory Pattern – Create Objects Without new
4. Singleton Pattern – One Instance Only
5. Decorator Pattern – Add Features Without Modifying Code
6. Revealing Module Pattern – Cleaner Public Interface
7. Strategy Pattern – Switch Algorithms at Runtime
Final Thoughts
Home Web Front-end H5 Tutorial A Guide to JavaScript Design Patterns

A Guide to JavaScript Design Patterns

Jul 29, 2025 am 04:11 AM
Design Patterns

The JavaScript design pattern is a reusable solution to common software design problems, helping to write maintainable, extensible, and well-structured code. 1. The module mode is encapsulated through IIFE or ES6 modules to protect private variables and avoid global pollution; 2. The observer mode allows object subscription to the main body changes, which is suitable for event processing and state updates, and is the basis of Redux and other libraries; 3. The factory mode dynamically creates objects at runtime and centrally manages object generation logic; 4. The singleton mode ensures that there is only one instance of a class, which is often used for configuration management but needs to be used with caution to avoid testing difficulties; 5. The decorator mode dynamically adds functions without modifying the original object, and is often used in logs, caches and other scenarios; 6. Reveals the module mode provides a clearer public interface by returning references to private functions to improve readability; 7. The policy mode encapsulates the algorithm into interchangeable policies, which facilitates switching of verification and other logic at runtime. Understanding these patterns can help read complex code, quickly debug and build a good architecture, but should be flexibly selected rather than blindly followed according to actual needs.

JavaScript design patterns are reusable solutions to common problems in software design. They help developers write maintainable, scalable, and organized code—especially important in large JavaScript applications. While JavaScript is flexible and doesn't enforce patterns, using them wisely improves code structure and team collaboration.

Here's a practical guide to the most useful JavaScript design patterns, explained in simple terms with real-world relevance.


1. Module Pattern – Keep Code Organized and Private

The Module Pattern is one of the most widely used patterns in JavaScript. It helps you encapsulate code, create private variables and functions, and expose only what's necessary.

Why use it?
Avoid polluting the global scope and protect internal logic from accidental changes.

How it works:
Use an IIFE (Immediately Invoked Function Expression) or ES6 modules to create a closure.

 const ShoppingCart = (function () {
  let items = []; // private

  function calculateTotal() {
    return items.reduce((sum, item) => sum item.price, 0);
  }

  return {
    addItem(item) {
      items.push(item);
    },
    getTotal() {
      return calculateTotal();
    }
  };
})();

ShoppingCart.addItem({ name: 'Laptop', price: 999 });
console.log(ShoppingCart.getTotal()); // 999

Note: Modern ES6 modules ( import / export ) have largely replaced the classic Module Pattern, but the concept of encapsulation remains key.


2. Observer Pattern – Handle Events and State Changes

This pattern lets objects (observers) subscribe to changes in another object (the subject). It's the foundation of event handling and reactive programming.

Use cases:

  • UI updates when data changes
  • Event systems (eg, button clicks, form inputs)
  • Implementing pub/sub systems
 class EventObserver {
  constructor() {
    this.observers = [];
  }

  subscribe(fn) {
    this.observers.push(fn);
  }

  unsubscribe(fn) {
    this.observers = this.observers.filter(subscriber => subscriber !== fn);
  }

  notify(data) {
    this.observers.forEach(fn => fn(data));
  }
}

const observer = new EventObserver();

const logData = data => console.log('Received:', data);
const uppercaseData = data => console.log('Uppercase:', data.toUpperCase());

observer.subscribe(logData);
observer.subscribe(uppercaseData);

observer.notify('hello'); 
// Output: 
// Received: hello
// Uppercase: HELLO

This pattern is behind libraries like Redux and frameworks like Vue and Angular.


3. Factory Pattern – Create Objects Without new

Use the Factory Pattern when you need to create multiple similar objects without tightly coupling your code to specific classes.

When to use:

  • You don't know the exact type of object needed until runtime
  • You want to centralize object creation logic
 function createPerson(type) {
  if (type === 'developer') {
    return {
      role: 'Developer',
      skills: ['JavaScript', 'React'],
      code() { console.log('Writing code...'); }
    };
  } else if (type === 'designer') {
    return {
      role: 'Designer',
      skills: ['Figma', 'Photoshop'],
      design() { console.log('Creating mockups...'); }
    };
  }
}

const dev = createPerson('developer');
dev.code(); // Writing code...

Keeps object creation logic clean and extendible.


4. Singleton Pattern – One Instance Only

Ensures a class has only one instance and provide a global point to access it.

Useful for:

  • Database connections
  • Configuration managers
  • Logging services
 let ConfigManager = (function () {
  let instance;

  function createInstance() {
    const object = { theme: 'dark', language: 'en' };
    return object;
  }

  return {
    getInstance() {
      if (!instance) {
        instance = createInstance();
      }
      return instance;
    }
  };
})();

const config1 = ConfigManager.getInstance();
const config2 = ConfigManager.getInstance();

console.log(config1 === config2); // true – same instance

Be cautious: Singletons can make testing harder and introduce global state.


5. Decorator Pattern – Add Features Without Modifying Code

Allows you to add behavior to objects dynamically without altering their structure.

Real-world use:

  • Adding logging, caching, or validation to functions
  • Used heavily in TypeScript decorators
 function withLogging(fn) {
  return function (...args) {
    console.log(`Calling ${fn.name} with`, args);
    const result = fn(...args);
    console.log(`Result:`, result);
    return result;
  };
}

function add(a, b) {
  return ab;
}

const addLogged = withLogging(add);
addLogged(2, 3);
// Logs: Calling add with [2, 3]
// Results: 5

This functional approach is common in modern JS and aligns well with higher-order functions.


6. Revealing Module Pattern – Cleaner Public Interface

An improvement over the classic Module Pattern. It lets you define all functions privately and selectively expose them.

 const TaskManager = (function () {
  let tasks = [];

  function add(task) {
    tasks.push(task);
  }

  function list() {
    return tasks;
  }

  // Reveal only what's needed
  return {
    add: add,
    list: list
  };
})();

Makes it clear which functions are public—improves readability and maintenance.


7. Strategy Pattern – Switch Algorithms at Runtime

Encapsulates different algorithms and make them interchangeable.

Example:
Validation logic for different form types.

 const validationStrategies = {
  email(value) {
    return value.includes('@') && value.includes('.');
  },
  password(value) {
    return value.length >= 8 && /\d/.test(value);
  },
  phone(value) {
    return /^\d{10}$/.test(value);
  }
};

function validate(input, type) {
  return validationStrategies[type](input);
}

console.log(validate('test@example.com', 'email')); // true
console.log(validate('pass1234', 'password')); // true

Promotes loose coupling and makes adding new strategies easy.


Final Thoughts

Design patterns aren't silver bullets—they're tools. Use them when they solve a real problem, not just because they're "best practice."

Some modern JavaScript (especially with React, Vue, etc.) abstracts these patterns away, but understanding them helps you:

  • Read complex codebases
  • Debug issues faster
  • Design better architectures

You don't need to memorize all patterns. Start with Module , Observer , and Factory —they're the most practical in day-to-day JS development.

Basically, know the patterns, but stay flexible.

The above is the detailed content of A Guide to JavaScript Design Patterns. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
The difference between design patterns and architectural patterns in Java framework The difference between design patterns and architectural patterns in Java framework Jun 02, 2024 pm 12:59 PM

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.

PHP Design Patterns: Test Driven Development in Practice PHP Design Patterns: Test Driven Development in Practice Jun 03, 2024 pm 02:14 PM

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.

Application of design patterns in Guice framework Application of design patterns in Guice framework Jun 02, 2024 pm 10:49 PM

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.

Analysis of the Decorator Pattern in Java Design Patterns Analysis of the Decorator Pattern in Java Design Patterns May 09, 2024 pm 03:12 PM

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.

Application of design patterns in Spring MVC framework Application of design patterns in Spring MVC framework Jun 02, 2024 am 10:35 AM

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.

What are the advantages and disadvantages of using design patterns in java framework? What are the advantages and disadvantages of using design patterns in java framework? Jun 01, 2024 pm 02:13 PM

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: Patterns used to solve specific software problems PHP Design Patterns: Patterns used to solve specific software problems Jun 01, 2024 am 11:07 AM

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.

The relationship between design patterns and test-driven development The relationship between design patterns and test-driven development May 09, 2024 pm 04:03 PM

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.

See all articles