JavaScript 设计模式是提高代码可维护性和扩展性的重要手段。以下是一些常用的 JavaScript 设计模式及其简要介绍。
单例模式 (Singleton)
单例模式确保一个类只有一个实例,并提供一个全局访问点。
class Singleton {
constructor() {
if (!Singleton.instance) {
Singleton.instance = this;
}
return Singleton.instance;
}
}
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // 输出:true
观察者模式 (Observer)
观察者模式定义对象间的一对多依赖关系,当一个对象改变状态时,所有依赖于它的对象都会得到通知并自动更新。
class Subject {
constructor() {
this.observers = [];
}
subscribe(observer) {
this.observers.push(observer);
}
notify() {
this.observers.forEach(observer => observer.update());
}
}
class Observer {
update() {
console.log('Observer notified!');
}
}
const subject = new Subject();
const observer = new Observer();
subject.subscribe(observer);
subject.notify(); // 输出:Observer notified!
装饰者模式 (Decorator)
装饰者模式动态地给一个对象添加一些额外的职责,而不改变其接口。
function Decorator(target) {
target.originalMethod = target.method;
target.method = function() {
console.log('Before method execution');
target.originalMethod();
console.log('After method execution');
};
}
class Component {
method() {
console.log('Method executed');
}
}
const decoratedComponent = new Component();
decoratedComponent.method(); // 输出:Before method execution
Method executed
After method execution
模板方法模式 (Template Method)
模板方法模式定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。
class TemplateMethod {
templateMethod() {
this.stepOne();
this.stepTwo();
this.stepThree();
}
stepOne() {
console.log('Step 1');
}
stepTwo() {
console.log('Step 2');
}
stepThree() {
console.log('Step 3');
}
}
class ConcreteTemplate extends TemplateMethod {
stepTwo() {
console.log('Custom Step 2');
}
}
const concreteTemplate = new ConcreteTemplate();
concreteTemplate.templateMethod(); // 输出:Step 1
Custom Step 2
Step 3
更多关于 JavaScript 设计模式的内容,您可以访问本站 JavaScript 设计模式教程。
JavaScript 设计模式