/*
单例设计模式
以前我写代码,都是以特别简单的方式来操作 Dom节点
没有从设计模式的角度来去编写代码
当我们会写代码了,就应该去考虑一点代码的质量
*/
//例如 现在我们有 两个按钮 需要相互操作内容
$('#btn_a').click(function () {
var a_text = '这是A的内容';
});
$('#btn_b').click(function () {
var b_text = '这是B的内容';
//现在问题就来了 我在这里怎么改变A中的 a_text 值呢
//一般的解决方式 ,就是a_text 弄成全局参数
// 那么问题就来了,这时候我们只解决了模块之间的通信,
// 为例解决这个问题,我们导致内存的泄露,数据的不安全性,以及元素的污染
//好吧~ 上面都是废话,谁突然就能理解这个,我们通俗点来说
//现在我们把a_text 弄好处成全局变量 ,本来它是属于A操作的内容
//现在全天下都能看到这个参数了,而且不需要经过A的同意 ,这就造成了-----不安全性
//内存是一个很宝贵的东西,现在a_text 全局的,他就要一直保持待命状态,无法销毁,变量的多了,就会造成内存负担过大 ------内存的泄露
});
// 那么单例设计模式就来了
var Demo_a = {
a_text: '这是属于A的内容',
init: function () {
this.render();
this.bind();
},
render: function () {
var me_a = this;
me_a.btn_a = $('#btn_a');
},
bind: function () {
var me_a = this;
me_a.btn_a.click(function () {
//需要的操作
me_a.setData();
});
},
setData: function () {
a_text += a_text + '我对这个A进行了一些不可描述的操作'
console.log(a_text);
}
}
var Demo_b = {
b_text: '这是属于B的内容',
init: function () {
this.render();
this.bind();
},
render: function () {
var me_b = this;
me_b.btn_b = $('#btn_b');
},
bind: function () {
var me_b = this;
me_b.btn_b.click(function () {
//需要的操作
me_b.setData();
});
},
setData: function () {
b_text += b_text + '我对这个B进行了一些不可描述的操作'
console.log(b_text);
//而且我们这里还可以叫A来一起进行不可描述的事情
var a_b_text = Demo_a.a_text + b_text;
console.log(a_b_text)
}
};
// 调用一下
Demo_a.init();
Demo_b.init();
/*
* 构造函数
* */
function Stroy(plot_me) {
if (!(this instanceof Stroy)) {
return new Stroy();
}
var _plot_me = '一般的情节'
if (plot_me) {
_plot_me = plot_me;
}
this.plot_me = _plot_me;
this.plot_a = '这是第一个情节';
this.plot_b = '这是第二个情节';
this.print = function () {
return '【故事线一】' + this.plot_a + '【故事线二】' + this.plot_b + '【自己的情节】' + this.plot_me;
}
}
var Lisi = Stroy('我自己编一个扯淡的情节');
//单例模式 跟 构造函数结合
var stroy_a = {
Stroy: function (plot_me) {
if (!(this instanceof Stroy)) {
return new Stroy();
}
var _plot_me = '一般的情节'
if (plot_me) {
_plot_me = plot_me;
}
this.plot_me = _plot_me;
this.plot_a = '这是第一个情节';
this.plot_b = '这是第二个情节';
this.print = function () {
return '【故事线一】' + this.plot_a + '【故事线二】' + this.plot_b + '【自己的情节】' + this.plot_me;
}
}
}
var stroy_b = {
Stroy: function (plot_me) {
if (!(this instanceof Stroy)) {
return new Stroy();
}
var _plot_me = '一般的情节'
if (plot_me) {
_plot_me = plot_me;
}
this.plot_me = _plot_me;
this.plot_a = '这是第一个情节';
this.plot_b = '这是第二个情节';
this.print = function () {
return '【故事线一】' + this.plot_a + '【故事线二】' + this.plot_b + '【自己的情节】' + this.plot_me;
}
}
}
var Lisi_a = stroy_a.Stroy('我用A出版社写了个扯淡的情节') ;
var Lisi_b = stroy_b.Stroy('我用B出版社写了另一个扯淡的情节') ;