要在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設計模式的簡單示例。要完全掌握設計模式,需要更深入的學習和實踐。