要在10分钟内掌握JavaScript设计模式是一项挑战,但可以简单了解一些常见的设计模式。
var Singleton = (function() {
var instance;
function createInstance() {
var object = new Object("I am the instance");
return object;
}
return {
getInstance: function() {
if(!instance) {
instance = createInstance();
}
return instance;
}
};
})();
var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // 输出 true
function ShapeFactory() {}
ShapeFactory.prototype.createShape = function(type) {
if(type === "circle") {
return new Circle();
} else if(type === "rectangle") {
return new Rectangle();
} else if(type === "triangle") {
return new Triangle();
}
};
function Circle() {
this.type = "circle";
}
function Rectangle() {
this.type = "rectangle";
}
function Triangle() {
this.type = "triangle";
}
var shapeFactory = new ShapeFactory();
var circle = shapeFactory.createShape("circle");
console.log(circle.type); // 输出 "circle"
function Subject() {
this.observers = [];
}
Subject.prototype.addObserver = function(observer) {
this.observers.push(observer);
};
Subject.prototype.removeObserver = function(observer) {
var index = this.observers.indexOf(observer);
if(index !== -1) {
this.observers.splice(index, 1);
}
};
Subject.prototype.notifyObservers = function() {
this.observers.forEach(function(observer) {
observer.update();
});
};
function Observer(name) {
this.name = name;
}
Observer.prototype.update = function() {
console.log(this.name + " received update");
};
var subject = new Subject();
var observer1 = new Observer("Observer 1");
var observer2 = new Observer("Observer 2");
subject.addObserver(observer1);
subject.addObserver(observer2);
subject.notifyObservers(); // 输出 "Observer 1 received update" 和 "Observer 2 received update"
这些是只是一些JavaScript设计模式的简单示例。要完全掌握设计模式,需要更深入的学习和实践。