阅读量:5
要在10分钟内掌握JavaScript设计模式是一项挑战,但可以简单了解一些常见的设计模式。
- 单例模式(Singleton Pattern):确保只有一个实例被创建,并提供全局访问点。
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
- 工厂模式(Factory Pattern):通过工厂方法创建对象,而不是使用构造函数。
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"
- 观察者模式(Observer Pattern):定义了一种发布-订阅模式,主题(Subject)维护一个观察者(Observer)列表,并在状态变化时通知观察者。
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设计模式的简单示例。要完全掌握设计模式,需要更深入的学习和实践。