JavaScript设计模式详解 - 6种常用模式
前言
在编程中,设计模式是一种可重用的解决方案,用于解决在软件设计中经常遇到的问题。设计模式可以提高代码的可读性、可维护性和可扩展性。本文将介绍JavaScript中的一些常用设计模式,并提供实现示例。
1. 单例模式(Singleton)
单例模式确保一个类只有一个实例,并提供一个全局访问点。在JavaScript中,可以使用对象字面量或闭包来实现单例模式。例如:
const Singleton = (function () {
let instance;
function createInstance() {
return {
attribute: "some value",
method: function () {
console.log("Do something");
}
};
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // 输出 true
2. 工厂模式(Factory)
工厂模式是一种创建对象的设计模式,它使用一个通用的接口来创建具体的对象。在JavaScript中,可以使用函数作为工厂。例如:
function CarFactory() {
this.createCar = function (brand) {
let car;
switch (brand) {
case "Toyota":
car = new Toyota();
break;
case "Honda":
car = new Honda();
break;
default:
car = new GenericCar();
}
return car;
};
}
function Toyota() {
this.name = "Toyota";
this.drive = function () {
console.log("Driving a Toyota");
};
}
function Honda() {
this.name = "Honda";
this.drive = function () {
console.log("Driving a Honda");
};
}
function GenericCar() {
this.name = "Generic Car";
this.drive = function () {
console.log("Driving a car");
};
}
const factory = new CarFactory();
const car = factory.createCar("Toyota");
car.drive(); // 输出 "Driving a Toyota"
3. 观察者模式(Observer)
观察者模式是一种行为设计模式,它定义了对象之间的一对多依赖关系。当一个对象的状态发生变化时,所有依赖它的对象都会收到通知。在JavaScript中,可以使用事件监听器实现观察者模式。例如:
class Subject {
constructor() {
this.observers = [];
}
addObserver(observer) {
this.observers.push(observer);
}
removeObserver(observer) {
const index = this.observers.indexOf(observer);
if (index > -1) {
this.observers.splice(index, 1);
}
}
notify(data) {
for (const observer of this.observers) {
observer.update(data);
}
}
}
class Observer {
update(data) {
console.log("Observer received data:", data);
}
}
const subject = new Subject();
const observer1 = new Observer();
const observer2 = new Observer();
subject.addObserver(observer1);
subject.addObserver(observer2);
subject.notify("Some data"); // 输出 "Observer received data: Some data" 两次
4. 策略模式(Strategy)
策略模式是一种行为设计模式,它定义了一系列算法,并将它们封装起来。这使得算法可以相互替换,而不影响使用它们的客户端。在JavaScript中,可以使用高阶函数实现策略模式。例如:
function shippingStrategy(strategy) {
return function (package) {
return strategy.calculate(package);
};
}
const UPS = {
calculate: function (package) {
// 计算UPS运费
return 10;
}
};
const FedEx = {
calculate: function (package) {
// 计算FedEx运费
return 15;
}
};
const shipping = shippingStrategy(UPS);
const cost = shipping({
weight: 2,
dimensions: { width: 10, height: 5, depth: 5 }
});
console.log(cost); // 输出 10
5. 适配器模式(Adapter)
适配器模式是一种结构设计模式,它允许不兼容的接口之间进行通信。适配器用于将一个类的接口转换为另一个类所期望的接口。在JavaScript中,可以使用函数作为适配器。例如:
class OldInterface {
oldMethod() {
console.log("Old method");
}
}
class NewInterface {
newMethod() {
console.log("New method");
}
}
function adapter(oldInterface) {
const newInterface = new NewInterface();
oldInterface.newMethod = function () {
newInterface.newMethod();
};
return oldInterface;
}
const old = new OldInterface();
const adapted = adapter(old);
adapted.newMethod(); // 输出 "New method"
6. 装饰器模式(Decorator)
装饰器模式是一种结构设计模式,它允许在运行时为对象添加新的行为,而无需修改其原始结构。在JavaScript中,可以使用高阶函数实现装饰器模式。例如:
function Component() {
this.operation = function () {
console.log("Component operation");
};
}
function ConcreteDecoratorA(component) {
const originalOperation = component.operation;
component.operation = function () {
originalOperation.call(component);
console.log("ConcreteDecoratorA operation");
};
return component;
}
function ConcreteDecoratorB(component) {
const originalOperation = component.operation;
component.operation = function () {
originalOperation.call(component);
console.log("ConcreteDecoratorB operation");
};
return component;
}
const component = new Component();
const decoratedA = ConcreteDecoratorA(component);
const decoratedB = ConcreteDecoratorB(decoratedA);
decoratedB.operation();
// 输出 "Component operation"
// 输出 "ConcreteDecoratorA operation"
// 输出 "ConcreteDecoratorB operation"
总结
设计模式可以提高代码的可读性、可维护性和可扩展性,因此在实际项目中应用它们非常有帮助。