js实现模式
JavaScript 设计模式的实现
JavaScript 设计模式是解决常见问题的可重用方案。以下是几种常用模式的实现方式。
单例模式
确保一个类只有一个实例,并提供全局访问点。
const Singleton = (function() {
let instance;
function createInstance() {
return new Object('I am the instance');
}
return {
getInstance: function() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true
观察者模式
定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖它的对象都会得到通知。
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 {
update(data) {
console.log(`Observer received: ${data}`);
}
}
const subject = new Subject();
const observer1 = new Observer();
const observer2 = new Observer();
subject.subscribe(observer1);
subject.subscribe(observer2);
subject.notify('Hello Observers!');
工厂模式
创建对象时不指定具体类,而是通过工厂方法决定实例化哪个类。
class Car {
constructor(options) {
this.wheels = options.wheels || 4;
this.color = options.color || 'white';
}
}
class Truck {
constructor(options) {
this.wheels = options.wheels || 6;
this.color = options.color || 'black';
}
}
class VehicleFactory {
createVehicle(options) {
if (options.type === 'car') {
return new Car(options);
} else if (options.type === 'truck') {
return new Truck(options);
}
}
}
const factory = new VehicleFactory();
const car = factory.createVehicle({ type: 'car', color: 'red' });
const truck = factory.createVehicle({ type: 'truck' });
装饰器模式
动态地给对象添加额外的职责,相比继承更加灵活。
class Coffee {
cost() {
return 5;
}
}
class MilkDecorator {
constructor(coffee) {
this.coffee = coffee;
}
cost() {
return this.coffee.cost() + 2;
}
}
class SugarDecorator {
constructor(coffee) {
this.coffee = coffee;
}
cost() {
return this.coffee.cost() + 1;
}
}
let coffee = new Coffee();
coffee = new MilkDecorator(coffee);
coffee = new SugarDecorator(coffee);
console.log(coffee.cost()); // 8
策略模式
定义一系列算法,封装每个算法,并使它们可以互相替换。

const strategies = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
multiply: (a, b) => a * b
};
class Calculator {
constructor(strategy) {
this.strategy = strategy;
}
execute(a, b) {
return this.strategy(a, b);
}
}
const addCalculator = new Calculator(strategies.add);
console.log(addCalculator.execute(5, 3)); // 8
const multiplyCalculator = new Calculator(strategies.multiply);
console.log(multiplyCalculator.execute(5, 3)); // 15
这些模式提供了解决特定问题的标准化方法,可以根据具体需求选择合适的模式。






