Skip to content

Instantly share code, notes, and snippets.

@hzhopen
Created March 24, 2014 06:24
Show Gist options
  • Save hzhopen/9735128 to your computer and use it in GitHub Desktop.
Save hzhopen/9735128 to your computer and use it in GitHub Desktop.
JavaScript设计模式-单例模式
JavaScript设计模式-单例模式
/*study*/
/**
* 使用单例模式创建一个应用程序名称空间
* 调用$(document).ready(myApp.init)
*/
var myApp = {
//初始化
init : function(){},
dshboard : function(){},
controlPanel : function(){},
appSettings : function(){}
}
/**
* 根据开发人员和网站结构,拆分单个单例模式。 这样开发人员负责自己的js文件,便于管理,防止冲突。
* 等到开发完成之后再把多个js文件合成一个js文件。减少与客户端的http连接次数。
*
*/
//一个站点一个js命名空间
var myApp = {
//common包含项目的通用代码,由主管负责
common : {
init : function(){}
}
}
//程序员A负责dashboard
myApp.dashboard = {
init : function(){
....
},
func1 : function(){},
func2 : function(){}
}
//程序员B负责controlPanel
myApp.controlPanel = {
...
}
/**
* Module模式
* 由yahoo首席js架构师 Douglas Crockford 发明
*
* 特点:
* 相对于单例模式,增加私有方法,私有属性的功能。
* 是一个自动执行的函数,也就是创建的时候返回公有方法和属性的对象
*/
var myApp = function(){
//私有变量和方法
var privateVarible = 1;
var privateFunction = function(){};
//返回对象包含公有属性和对象
return {
init : function(){},
publicVariable : 42,
publicFunction : function(){
//invoke private function or varible
privateFunction();
}
}
}(/*自动调用*/);
//扩展Module模式
myApp.ExtendModul = function(){
//私有的部分
//返回公有
return {
...
}
}();
/**
* Garber-lrish模式
* 这个模式提供一个简洁的工具,为在$(function(){})中运行的代码提供一个统一的、可伸缩、可维护的方法
* [= = ! 好像用处不大]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment