单例模式顾名思义就是说在实例化对象**的过程中, 只能存在一个实例对象, 经典的实现方式就是创建一个类, 这个类包含一个方法, 这个方法在没有对象存在的情况下, 将会创建一个新的实例对象, 如果对象存在, 这个方法只是返回这个对象的引用, 多数用于例如弹框(Modal)之类等, 更多的还比如是全局存储的对象流行框架中使用的如 Vux 和 Redux**

    1. class Singleton {
    2. constructor() {
    3. this.state = false;
    4. this.instance = null;
    5. }
    6. getInstance() {
    7. if(!this.instance) {
    8. this.instance = new Singleton();
    9. }
    10. return this.instance;
    11. }
    12. show() {
    13. if(this.state) {
    14. console.log('已经显示了');
    15. return;
    16. }
    17. this.state = true;
    18. console.log('>>>>>> show');
    19. }
    20. hide() {
    21. if(!this.state) {
    22. console.log('已经隐藏掉了>>>>>>>>>');
    23. }
    24. this.state = false;
    25. console.log('>>>>>>>>>>>>>>>>> hide');
    26. }
    27. }
    28. const single = new Singleton();
    29. single.show()
    30. single.show();
    31. single.hide();
    32. single.hide();

    像上边代码一样, 单例模式是只允许存在一个实例对象, 还有一种是可以使用对象直接创建, 可以避免有更多的变量命名冲突, 防止别人修改代码造成的 **bug**