JavaScript 中常见的设计模式有以下几种:
1. 单例模式:
const Singleton = (function () {
let instance;
function createInstance() {
const object = new Object("I am the instance");
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
2. 工厂模式:
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
function Truck(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
function VehicleFactory() {}
VehicleFactory.prototype.vehicleClass = Car;
VehicleFactory.prototype.createVehicle = function (make, model, year) {
if (this.vehicleClass) {
return new this.vehicleClass(make, model, year);
} else {
throw new Error('Invalid vehicle class');
}
};
3. 观察者模式:
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) {
this.observers.forEach(observer => observer.update(data));
}
}
class Observer {
update(data) {
console.log('Received data:', data);
}
}
4. 模块模式:
const Module = (function () {
let privateVar = 'I am private';
function privateMethod() {
console.log(privateVar);
}
return {
publicMethod: function () {
privateMethod();
}
};
})();
5. 代理模式:
class Image {
constructor(url) {
this.url = url;
this.loadImage();
}
loadImage() {
console.log(`Loading image from ${this.url}`);
}
}
class ImageProxy {
constructor(url) {
this.url = url;
this.image = null;
}
showImage() {
if (!this.image) {
this.image = new Image(this.url);
}
this.image.loadImage();
}
}
这些设计模式在不同的场景中可以帮助开发者更有效地组织和管理代码,提高代码的可维护性和可扩展性。但过度使用或不恰当使用也可能导致代码复杂性增加。
领取专属 10元无门槛券
手把手带您无忧上云