es6实现单例模式及其应用

单例模式的定义是:保证一个类仅有一个实例,并提供一个访问它的全局访问点

单例模式能在合适的时候创建对象,并且创建唯一的一个。
比如一个网站的登录,点击登录后弹出一个登录弹框,即使再次点击,也不会再出现一个相同的弹框。又或者一个音乐播放程序,如果用户打开了一个音乐,又想打开一个音乐,那么之前的播放界面就会自动关闭,切换到当前的播放界面、这些都是单例模式的应用场景。

要实现一个单例模式,一个经典的方式是创建一个类,类中又一个方法能创建该类的实例对象,还有一个标记,记录是否已经创建过了实例对象,如果对象已经存在,就返回第一个实例化对象的引用。

单例模式应用实例
我们用一个生活中常见的一个场景来说明单例模式的应用。
任意一个网站,点击登录按钮,只会弹出有且仅有一个登录框,即使后面再点击登录按钮,也不会再弹出多一个弹框。这就是单例模式的典型应用。接下来我们实现它。为了注重单例模式的展示,我们把登录框简化吧��

在页面上设置一个按钮

<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);
        }

那么接下来要用单例模式实现,点击按钮出现有且仅有一个浮窗,方法就是在构造函数中创建一个标记,第一次点击时创建一个浮窗,用来改变标记的状态,再次点击按钮时,根据标记的状态判断是否要再创建一个浮窗。

//  静态方法作为广为人知的接口
            static getInstance(){
                //  根据标记的状态判断是否要再添加浮窗,如果标记为空就创建一个浮窗
                if(!this.instance){
                    this.instance = new loginLayer();
                }
                return this.instance;
            }

当然不要忘记为浮窗添加一个样式,让浮窗显示啦

.login-layer{
    width:200px;
    height:200px;
    background:rgba(0,0,0,.6);
    text-align:center;
    line-height:200px;
    display:inline-block;
}

完整代码如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
.login-layer{
    width:200px;
    height:200px;
    background: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>

这里写图片描述

猜你喜欢

转载自blog.csdn.net/zjsfdx/article/details/81505906