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'); // 發佈一個字符串到全部訂閱者
相關文章
相關標籤/搜索