当前位置:网站首页>Monomer mode

Monomer mode

2022-06-09 11:02:00 Qwe7

3、 ... and 、 Monomer mode

Monomer pattern is one of the most commonly used design patterns . Monomer mode is to create objects using methods , No matter how many times we create an object, it points to the same

1、 Normal way to create objects

<!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>Document</title>
    <script>
    
    function notSingle() {
        return {
            a: 1
        }
    }

    var a = notSingle()
    var b = notSingle()

    console.log(a === b) //  Print  false

    function notSingle2() {
        this.a = 123
    }

    var a1 = new notSingle2()
    var a2 = new notSingle2()

    console.log(a1 === b1); //  Print  false

    //  Whether using functions , Or in the case of constructors , The objects we create are independent of each other 
    //  In the vast majority of cases , This is also the result we expect , That's fine 
    //  When in some cases , We need the returned data created by them to be the object data that has been created , Instead of creating new objects 

    
    </script>
</head>
<body>
    
</body>
</html>

2、 Create objects in monomer mode

<!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>Document</title>
    <script>
    
    var _unique = null;

    function createSingle() {
        var obj = {
            a: 1
        }
        if (_unique === null) {
            _unique = obj
        }
        return _unique
    }

    var a = createSingle()
    var b = createSingle()

    console.log(a === b) //  Print true

    var a1 = createSingle()
    _unique = null //  Modified in the middle _unique Will result in inconsistent returned objects 
    var b1 = createSingle()

    console.log(a1 === b1) // false

    var createSingle1 = (function() {
        var _unique = null;

        function single() {
            return {
                a: 1
            }
        }

        return function() {
            if (_unique === null) {
                // _unique = {
                //     a: 1
                // }
                _unique = single()
            } else {
                return _unique
            }
        }
    })()

    var a2 = createSingle1()
    var b2 = createSingle1()
    console.log(a2 === b2)

    </script>
</head>
<body>
    
</body>
</html>
原网站

版权声明
本文为[Qwe7]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091019248946.html