-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathsingleton.html
63 lines (62 loc) · 1.41 KB
/
singleton.html
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
58
59
60
61
62
63
<html>
<head>
<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.js"></script>
<style type="text/css">
.demo{
border:1px solid coral;
padding:30px;
margin:5px;
}
</style>
</head>
<body>
<div>singleton设计模式</div>
<div class="demo decorator">
<div>singleton举例子</div>
<button id='s-b-1'>点击</button>
<div>
result is ---- <span id='s1'>0</span>
</div>
<script type="text/javascript">
var singleton = function(){
var instance;
var createInstance = function(){
this.a = 1;
this.b = 2;
};
return {
getInstance: function() {
if (!instance) {
instance = new createInstance();
}
return instance;
}
}
}
</script>
<script type="text/javascript">
var Factory = singleton()
var singleton_1 = Factory.getInstance();
$('#s-b-1').click(function(){
$('#s1').html(singleton_1.a);
singleton_1.a++
})
</script>
<button id='s-b-2'>点击</button>
<div>
result is ---- <span id='s2'>0</span>
</div>
<script type="text/javascript">
var singleton_2 = Factory.getInstance();
$('#s-b-2').click(function(){
$('#s2').html([
singleton_2.a ,
'第二个实例和第一个实例指向同一个引用这句话是',
singleton_2===singleton_1&&"正确的"
].join(''));
singleton_1.a++
})
</script>
</div>
</body>
</html>