前端常用设计模式之单例模式
Posted !win !
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了前端常用设计模式之单例模式相关的知识,希望对你有一定的参考价值。
前情
在前端开发越来越复杂的今天,越来越需要一些设计模式来提高开发质量和效率
定义
属于创建型模式,这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。
代码演示
通过静态属性实现单例
class Person{
static instance;
constructor(name) {
if (!Person.instance) {
Person.instance = this;
} else {
return Person.instance;
}
this.name = name;
}
}
let zhangsan = new Person("张三");
let lisi = new Person("李四");
console.log(zhangsan, lisi);
// Person { name: \'张三\' } Person { name: \'张三\' }
通用的单例实现
class Person{
constructor(name) {
this.name = name;
}
}
// 通用单例
function createInstance(fn){
let instance;
return function(...args) {
if (!instance) {
instance = new fn(...args);
}
return instance;
}
}
let singlePerson = createInstance(Person);
let zhangsan = singlePerson("张三");
let lisi = singlePerson("李四");
console.log(zhangsan, lisi);
// Person { name: \'张三\' } Person { name: \'张三\' }
实际应用
单例实现弹窗简易弹窗组件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>单例弹窗</title>
<style>
html,body{
padding: 0;
margin: 0;
}
body{
background-color: aquamarine;
}
.dialog{
width: 300px;
height: 150px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 1px solid #ccc;
border-radius: 2px;
display: flex;
justify-content: center;
align-items: center;
background-color: #fff;
}
.close{
padding: 5px;
position: absolute;
top: 3px;
right: 3px;
cursor: pointer;
}
</style>
</head>
<body>
<button id="dialogBtn">弹窗</button>
<script>
class Dialog{
constructor() {
this.dialog = document.createElement(\'div\');
this.dialog.className = "dialog";
this.dialog.style.display = "none";
this.content = document.createElement(\'div\');
this.close = document.createElement(\'span\');
this.close.innerHTML = "X";
this.close.className = "close";
this.dialog.appendChild(this.content);
this.dialog.appendChild(this.close);
document.body.appendChild(this.dialog);
this.show = false;
let self = this;
this.close.onclick = function() {
self.hideDlg();
};
}
showDlg(tips) {
if (this.isShow) {
return;
}
this.content.innerHTML = tips;
this.dialog.style.display = "flex";
this.isShow = true;
}
hideDlg() {
if (!this.isShow) {
return;
}
this.dialog.style.display = "none";
this.isShow = false;
}
}
// 通用单例
function createInstance(fn){
let instance;
return function(...args) {
if (!instance) {
instance = new fn(...args);
}
return instance;
}
}
let singleDialog = createInstance(Dialog);
let dialog0 = singleDialog();
let dialog1 = singleDialog();
document.getElementById(\'dialogBtn\').onclick = function() {
dialog0.showDlg(\'这是弹窗测试0\');
dialog1.showDlg(\'这是弹窗测试1\');
}
</script>
</body>
</html>
好好学习!天天向上!
以上是关于前端常用设计模式之单例模式的主要内容,如果未能解决你的问题,请参考以下文章