JavaScript Design Patterns: Factory, Singleton, and Observer
Jul 29, 2025 am 01:39 AMFactory mode is used to create objects without exposing construction logic, and generate different types of objects through a unified interface, which is suitable for creating scenarios of multiple similar types of objects; 2. Singleton mode ensures that a class has only one instance and provides global access points, which are often used in scenarios such as configuration management and loggers that require a single state; 3. Observer mode establishes a one-to-many dependency relationship, which automatically notifies all observers when the subject state changes, and is widely used in event systems and data binding. These three modes solve the problems of object creation, instance uniqueness and state response, and use them in combination can improve the modularity, maintainability and scalability of the code.
Factory , Singleton , and Observer in the JavaScript design pattern are three very practical and common patterns that can help us write more modular, maintainable and extensible code. The following are their uses, implementation methods and usage scenarios.

1. Factory Pattern
Factory pattern is used to create objects without exposing specific construct logic. It generates different types of objects through a unified interface, which is particularly suitable for situations where object creation is logically complex or needs to dynamically determine the type according to conditions.
Use scenarios:
- Create multiple objects of similar types (such as different types of users, UI components, etc.)
- Avoid repeated
new
operations and conditional judgments scattered throughout the code
Sample code:
class Dog { speak() { return "Woof!"; } } class Cat { speak() { return "Meow!"; } } class AnimalFactory { createAnimal(type) { if (type === "dog") { return new Dog(); } else if (type === "cat") { return new Cat(); } throw new Error("Unknown animal type"); } } // Use const factory = new AnimalFactory(); const dog = factory.createAnimal("dog"); const cat = factory.createAnimal("cat"); console.log(dog.speak()); // Woof! console.log(cat.speak()); // Meow!
? Advantages : Decoupled object creation and use, making it easy to expand new types.
2. Singleton Pattern
Singleton pattern ensures that a class has only one instance and provides a global access point. In JavaScript, since objects are reference types, implementing singletons is relatively simple.
Use scenarios:
- Global configuration management
- Logger
- Database connection pool
- State management (such as Redux store is also a singleton in nature)
Implementation method:
class Database { constructor() { if (Database.instance) { return Database.instance; } this.url = "localhost:3000"; Database.instance = this; return this; } connect() { console.log("Connected to DB at " this.url); } } // Use const db1 = new Database(); const db2 = new Database(); console.log(db1 === db2); // true
?? Note: In the constructor, determine whether an instance already exists. If it exists, return the existing instance to avoid repeated creation.
? Advantages : Save resources and ensure the overall state is consistent.
?Note : Overuse may make the code difficult to test or have high coupling.
3. Observer Pattern
The observer pattern defines a one-to-many dependency. When an object's state changes, all objects that depend on it will be automatically notified. It is the basis of event systems and responsive programming.
Use scenarios:
- Event listening mechanism (such as DOM events)
- Data binding (such as Vue's responsive principle)
- Subscription updates in status management
Sample code:
class Subject { constructor() { this.observers = []; } subscribe(observer) { this.observers.push(observer); } unsubscribe(observer) { this.observers = this.observers.filter(obs => obs !== observer); } notify(data) { this.observers.forEach(observer => observer.update(data)); } } class Observer { constructor(name) { this.name = name; } update(data) { console.log(`${this.name} received:`, data); } } // Use const subject = new Subject(); const observer1 = new Observer("Alice"); const observer2 = new Observer("Bob"); subject.subscribe(observer1); subject.subscribe(observer2); subject.notify("New message!"); // Alice received: New message! // Bob received: New message! subject.unsubscribe(observer1); subject.notify("Second message!"); // Bob received: Second message!
? Advantages : loosely coupled, supports dynamic subscription/cancellation, suitable for asynchronous communication.
? Tips: In modern JS, you can use
EventTarget
or publish/subscribe (Pub/Sub) mode to simplify the implementation.
Summary and comparison
model | use | Core idea |
---|---|---|
Factory | Create an object | Encapsulation creation logic, unify interface |
Singleton | Guaranteed unique instance | Global access only one instance |
Observer | State changes notify dependants | Publish-subscribe, automatic update |
These three modes are often used in actual projects. for example:
- Manage global status with Singleton
- Use Observer to listen for state changes and refresh the UI
- Dynamically create components or services with Factory
Basically that's it. Mastering them can make your JavaScript architecture clearer and easier to deal with complex business logic.
The above is the detailed content of JavaScript Design Patterns: Factory, Singleton, and Observer. 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.
