《JavaScript 面向对象编程指南》笔记

单例模式

1
2
3
4
5
6
function Logger() {
if (!Logger.single_instance) {
Logger.single_instance = this;
}
return Logger.single_instance;
}

工厂模式

创建型模式。当我们有多个相似的对象而又不知道应该先使用哪种时,考虑工厂模式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var MYAPP = {};
MYAPP.dom = {};
MYAPP.dom.Text = function(url) {
this.url = url;
this.insert = function(there) {
var txt = document.createTextNode(this.url);
where.appendChild(txt);
}
}
MYAPP.dom.Link = function(url) {
this.url = url;
this.insert = function(there) {
var link = document.createElement('a');
link.href = this.url;
link.appendChild(document.createTextNode(this.url));
where.appendChild(link);
}
}
MYAPP.dom.Image = function(url) {
this.url = url;
this.insert = function(there) {
var img = document.createElement('img');
img.src = this.url;
where.appendChild(img);
}
}

// 调用
var url = './test.jpg';
var o = new MYAPP.dom.Image(url);
o.insert(document.body);

装饰器模式

结构性模式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var tree = {};
tree.decorate = function() {
alert('Make sure the tree won\'t fall');
}
tree.getDecorator = function(deco) {
tree[deco].prototype = this;
return new tree[deco];
}
tree.RedBalls = function() {
this.decorate = function() {
this.RedBalls.prototype.decorate();
alert('Put on some red balls');
}
}
tree.BlueBalls = function() {
this.decorate = function() {
this.BlueBalls.prototype.decorate();
alert('Put on some blue balls');
}
}

tree.getDecorator('RedBalls');
tree.getDecorator('BlueBalls');
tree.decorate();

观察者模式

发布-订阅模式,是一种行为型模式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
var observer = {
addSubscriber: function(callback)
{
if(typeof callback === 'function')
{
this.subscribers[this.subscribers.length] = callback;
}
},
removeSubscriber: function(callback)
{
for(var i = 0; i < this.subscribers.length; ++i)
{
if(this.subscribers[i] === callback)
{
delete this.subscribers[i];
}
}
},
publish: function(what)
{
for(var i = 0; i < this.subscribers.length; ++i)
{
if(typeof this.subscribers[i] === 'function')
{
this.subscribers[i](what);
}
}
},
make: function(o)
{
for(var i in this)
{
if(this.hasOwnProperty(i))
{
o[i] = this[i];
o.subscribers = [];
}
}
}
}

var blogger = {
writeBlogPost: function() {
var content = 'Today is ' + new Date();
this.publish(content);
}
}
observer.make(blogger);

var jack = {
read: function(what) {
console.log("I just read that " + what);
}
}
blogger.addSubscriber(jack);

blogger.writeBlogPost();