We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
定义: 一个类只有一个实例,并提供访问它的全局访问点。
用一个变量来标记当前是否已经为某个类创建了对象。
透明单例模式
var createDiv = (function(){ var instance; var createDiv = function(html){ if(instance){ return instance; } this.html = html; this.init(); return instance = this; } createDiv.prototype.init = function(){ var div = document.createElement('div'); div.innerHTML = this.html; document.body.appendChild(div); } return createDiv; })()
代理实现单例模式
var createDiv = function(html){ this.html = html; this.init() } createDiv.prototype.init = function(){ var div = document.createElement('div'); div.innerHTML = this.html; document.body.appendChild(div); } var ProxySingletonCreateDiv = (function(){ var instance; return function(html){ if(!instance){ instance = new createDiv(html); } return instance; } })()
惰性单例模式
var getSingleton = function(fn){ var result; return function(){ return result || (result = fn.apply(this,arguments)) } } var createLoginLayer = function(){ var div = document.createElement( 'div' ); div.innerHTML = '我是登录浮窗'; div.style.display = 'none'; document.body.appendChild( div ); return div; }; var createSingleLoginLayer = getSingle( createLoginLayer ); document.getElementById( 'loginBtn' ).onclick = function(){ var loginLayer = createSingleLoginLayer(); loginLayer.style.display = 'block'; };
创建对象和管理单例的职责被分布在两个不同的方法中,这两个方法组合起来才具有单例模式的威力。
The text was updated successfully, but these errors were encountered:
No branches or pull requests
单例模式
定义: 一个类只有一个实例,并提供访问它的全局访问点。
透明单例模式
代理实现单例模式
惰性单例模式
The text was updated successfully, but these errors were encountered: