引子

编程最重要的是什么? 是思想!设计模式中蕴含着很多的编程思想,今天就聊聊一些常用的设计模式吧,以及他们的应用场景示例

什么是设计模式

设计模式(Design pattern)代表了最佳的实践。设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案。这些解决方案是众多软件开发人员经过相当长的一段时间的试验和错误总结出来的。 设计模式是一套被反复使用的、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了重用代码、让代码更容易被他人理解、保证代码可靠性

常用的设计模式

单例模式

单例模式是最简单的设计模式之一, 这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不一定需要实例化该类的对象。

场景示例: 设计一个轻提示组件 消息展示2秒自动消失 多个消息排队展示

const Toast = (function () {
    const el = document.createElement('div')
    el.style.cssText = `
        position: fixed;
        left: 50%;
        top: 70%;
        display:none;
        background-color: rgba(0,0,0,.7);
        color: #fff;
        font-size:30px;
        border-radius: 5px;
        padding: 15px 25px; 
    transform: translateX(-50%);
    `
    document.documentElement.appendChild(el)
    let timer;
    const _instence = {
        el,
        // 存储需要展示的文本栈
        toastList: [],
        // 推送提示文本入栈
        showToast(text) {
            this.toastList.push(text)
            if (!timer) this.show()
        },
        show() {
            const text = this.toastList.splice(0, 1)[0]
            if (text !== undefined) {
                el.style.display = 'block'
                el.innerText = text
                timer = setTimeout(() => {
                    this.show()
                }, 2000)
            } else {
                el.innerText = ''
                el.style.display = 'none'
                timer = null
            }
        }
    }

    _instence.__proto__ = Toast.prototype

    function Toast() {
        return _instence
    }

    return Toast
})()

const toast = new Toast()
const toast1 = new Toast()

console.log(toast == toast1) // true


效果示意: 2021-11-02 13.56.45.gif

观察者模式

当对象间存在一对多关系时,则使用观察者模式。比如,当一个对象被修改时,则会自动通知依赖它的对象。观察者模式属于行为型模式。

场景示例: '仿照vue实现双向数据绑定'

么空写 等闲下来再写


目录