设计模式是解决软件设计中常见问题的通用模板,它们可以帮助开发人员编写可重用、可维护和可理解的代码,在 JavaScript 中,有许多不同的设计模式,如工厂模式、单例模式、观察者模式等。

网站建设哪家好,找创新互联!专注于网页设计、网站建设、微信开发、微信小程序、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了蒲县免费建站欢迎大家使用!
1、工厂模式
工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式,在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,而是使用一个共同的接口来指向新创建的对象。
class Car {
constructor(options) {
this.doors = options.doors || 4;
this.state = options.state || "brand new";
this.color = options.color || "silver";
}
}
class Truck {
constructor(options) {
this.state = options.state || "used";
this.wheelSize = options.wheelSize || "large";
this.color = options.color || "blue";
}
}
class VehicleFactory {
createVehicle(options) {
switch (options.vehicleType) {
case 'car':
return new Car(options);
case 'truck':
return new Truck(options);
// ...
}
}
}
2、单例模式
单例模式是一种创建型设计模式,它保证一个类只有一个实例,并提供一个全局访问点,这在需要频繁创建和销毁的对象时非常有用。
let Singleton = (function () {
let instance;
function createInstance() {
let object = new Object("I am the instance");
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
},
};
})();
let instance1 = Singleton.getInstance();
let instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true
3、观察者模式
观察者模式是一种行为设计模式,它定义了对象之间的一对多依赖关系,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新。
class Subject {
constructor() {
this.observers = [];
}
subscribe(observer) {
this.observers.push(observer);
}
unsubscribe(observer) {
this.observers = this.observers.filter((obs) => observer !== obs);
}
fire(action) {
this.observers.forEach((observer) => {
observer.update(action);
});
}
}
class Observer {
constructor(state) {
this.state = state;
this.initialState = state;
}
update(action) {
switch (action.type) {
case 'INCREMENT':
this.state = ++this.state;
break;
case 'DECREMENT':
this.state = this.state;
break;
default:
this.state = this.initialState;
}
}
}