js常用设计模式的实现思路,单例,工厂,代理,装饰,观察者模式等

 1     // 1) 单例: 任意对象都是单例,无须特别处理
 2 
 3     var obj = {name: 'michaelqin', age: 30};
 4 
 5     // 2) 工厂: 就是同样形式参数返回不同的实例
 6     function Person() { this.name = 'Person1'; }
 7     function Animal() { this.name = 'Animal1'; }
 8 
 9     function Factory() {}
10     Factory.prototype.getInstance = function(className) {
11         return eval('new ' + className + '()');
12     }
13 
14     var factory = new Factory();
15     var obj1 = factory.getInstance('Person');
16     var obj2 = factory.getInstance('Animal');
17     console.log(obj1.name); // Person1
18     console.log(obj2.name); // Animal1
19 
20     //3) 代理: 就是新建个类调用老类的接口,包一下
21     function Person() { }
22     Person.prototype.sayName = function() { console.log('michaelqin'); }
23     Person.prototype.sayAge = function() { console.log(30); }
24 
25     function PersonProxy() {
26         this.person = new Person();
27         var that = this;
28         this.callMethod = function(functionName) {
29             console.log('before proxy:', functionName);
30             that.person[functionName](); // 代理
31             console.log('after proxy:', functionName);
32         }
33     }
34 
35     var pp = new PersonProxy();
36     pp.callMethod('sayName'); // 代理调用Person的方法sayName()
37     pp.callMethod('sayAge'); // 代理调用Person的方法sayAge()
38 
39     //4) 观察者: 就是事件模式,比如按钮的onclick这样的应用.
40     function Publisher() {
41         this.listeners = [];
42     }
43     Publisher.prototype = {
44         'addListener': function(listener) {
45             this.listeners.push(listener);
46         },
47 
48         'removeListener': function(listener) {
49             delete this.listeners[listener];
50         },
51 
52         'notify': function(obj) {
53             for(var i = 0; i < this.listeners.length; i++) {
54                 var listener = this.listeners[i];
55                 if (typeof listener !== 'undefined') {
56                     listener.process(obj);
57                 }
58             }
59         }
60     }; // 发布者
61 
62     function Subscriber() {
63 
64     }
65     Subscriber.prototype = {
66         'process': function(obj) {
67             console.log(obj);
68         }
69     }; // 订阅者
70 
71     var publisher = new Publisher();
72     publisher.addListener(new Subscriber());
73     publisher.addListener(new Subscriber());
74     publisher.notify({name: 'michaelqin', ageo: 30}); // 发布一个对象到所有订阅者
75     publisher.notify('2 subscribers will both perform process'); // 发布一个字符串到所有订阅者
原文地址:https://www.cnblogs.com/Lewiskycc/p/8109182.html