我们用一个生活中常见的一个场景来说明单例模式的应用。
任意一个网站,点击登录按钮,只会弹出有且仅有一个登录框,即使后面再点击登录按钮,也不会再弹出多一个弹框。这就是单例模式的典型应用。接下来我们实现它。为了注重单例模式的展示,我们把登录框简化吧😜
在页面上设置一个按钮
<button id="loginBtn">登录</button>
为这个按钮添加点击事件
const btn = document.getElementById('loginBtn');
btn.addEventListener('click', function() {
loginLayer.getInstance();
}, false);
我们先给一个初始化方法init,在点击按钮之后,在页面上添加一个框框(权当登录框了)
init() {
var div = document.createElement('div');
div.classList.add('login-layer');
div.innerHTML = "我是登录浮窗";
document.body.appendChild(div);
}
那么接下来要用单例模式实现,点击按钮出现有且仅有一个浮窗,方法就是在构造函数中创建一个标记,第一次点击时创建一个浮窗,用改变标记的状态,再次点击按钮时,根据标记的状态判断是否要再创建一个浮窗。
上源码:
class loginLayer {
constructor() {
// 判断页面是否已有浮窗的标记
this.instance = null;
this.init();
}
init() {
var div = document.createElement('div');
div.classList.add('login-layer');
div.innerHTML = "我是登录浮窗";
document.body.appendChild(div);
}
// 静态方法作为广为人知的接口
static getInstance() {
// 根据标记的状态判断是否要再添加浮窗,如果标记不为空就创建一个浮窗
if(!this.instance) {
this.instance = new loginLayer();
}
return this.instance;
}
}
当然不要忘记为浮窗添加一个样式,让浮窗显示啦
.login-layer {
width: 200px;
height: 200px;
background-color: rgba(0, 0, 0, .6);
text-align: center;
line-height: 200px;
display: inline-block;
}
最后奉上该实例的源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>单例实现登录弹窗</title>
<style>
.login-layer {
width: 200px;
height: 200px;
background-color: rgba(0, 0, 0, .6);
text-align: center;
line-height: 200px;
display: inline-block;
}
</style>
</head>
<body>
<button id="loginBtn">登录</button>
<script>
const btn = document.getElementById('loginBtn');
btn.addEventListener('click', function() {
loginLayer.getInstance();
}, false);
class loginLayer {
constructor() {
this.instance = null;
this.init();
}
init() {
var div = document.createElement('div');
div.classList.add('login-layer');
div.innerHTML = "我是登录浮窗";
document.body.appendChild(div);
}
static getInstance() {
if(!this.instance) {
this.instance = new loginLayer();
}
return this.instance;
}
}
</script>
</body>
</html>
内容版权声明:除非注明,否则皆为本站原创文章。
