Contents
new
出SingleObject
getInstance()
方法返回SingleObject
对象单例模式需要用到java的private
特性
– java实现
public class SingleObject{
//注意,私有化构造函数,外部不能new,只能内部new
private SingleObject(){
}
//唯一被new出来的对象
private SingleObject instance = null;
//获取唯一对象的接口
public SingleObject getInstance(){
if(instance == null){
//只new一次
instance = new SingleObject();
}
return instance
}
//对象方法
public void login(){
System.out.print('login...')
}
}
//js模拟实现单例模式
class SingleObject{
login(){
console.log('login....')
}
}
//定义一个SingleObject对象的getInstance静态方法
//注意getInstance是一个自执行函数 funa()()
SingleObject.getInstance = (function () {
let instance //定义一个唯一对象
//闭包
return function () {
//如果instance 不存在 就只new一次
if(!instance){
instance = new SingleObject()
}
return instance
}
//返回一个instance
})()
let obj1 = SingleObject.getInstance()
obj1.login()
let obj2 = SingleObject.getInstance()
obj2.login()
console.log('obj1===obj2',obj1===obj2)
let obj3 = new SingleObject()
obj3.login()
console.log('obj1===obj3',obj1===obj3)
login
打印了两次,而且obj1===obj2
说明两个对象完全相等new
出来的SingelObject
发现与单例模式实现的并不是同一个对象 //jq只有一个$
if(window.jQuery !==null){
return window.jQuery
}else{
//初始化$
}
class LoginForm{
constructor(){
this.state = 'hide'
}
show(){
if(this.state === 'show'){
console.log('已经显示')
return
}
this.state = 'show';
console.log('登陆框显示 success')
}
hide(){
if(this.state === 'hide'){
console.log('已经隐藏')
return
}
this.state = 'hide';
console.log('登陆框隐藏 success')
}
}
LoginForm.getInstance = (function () {
let instance
return function () {
if(!instance){
instance = new LoginForm()
}
return instance
}
})()
//测试
let login1 = LoginForm.getInstance()
login1.show()
let login2 = LoginForm.getInstance()
login2.hide()
console.log('login1 === login2',login2===login1)