观察者模式 简介


<!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>
</head>

<body>
    <!-- <script>
        // 普通观察者模式
        // 发布者
        let rose = {
            // 存储内容 
            user: [],
            addUser: function (fn) {
                if (typeof (fn) !== 'function') {
                    throw '非法操作!'
                }
                this.user.push(fn);


            },
            removeUser: function (fn) {
                if (typeof (fn) != 'function') {
                    throw '非法操作!'
                }

                for (let i = 0; i < this.user.length; i++) {
                    if (this.user[i] == fn) {
                        this.user.splice(i, 1);
                    }
                }

            },
            // 执行方法 全部执行
            eat: function () {
                for (let i = 0; i < this.user.length; i++) {
                    this.user[i]()
                }
            }
        }

        // 观察者
        let jack_eat = {
            eat: function () {
                console.log('jack去吃饭了!')
            }
        }

        let tom_eat = {
            eat: function () {
                console.log('tom去吃饭了!')
            }

        }

        // 注册观察者
        rose.addUser(jack_eat.eat)
        rose.addUser(tom_eat.eat)

        // 执行
        rose.eat()

        // 解除观察者
        rose.removeUser(tom_eat.eat)
        // 执行
        rose.eat()
    </script> -->
    <!-- <script>
        //  多个发布者

        // 发布者模板
        let publiUser = {
            user: [],
            addUser: function (fn) {
                if (typeof fn != 'function') {
                    throw '非法参数!'
                }
                this.user.push(fn)
            },
            removeUser: function (fn) {
                for (let i = 0; i < this.user.length; i++) {
                    if (this.user[i] == fn) {
                        this.user.splice(i, 1)
                    }
                }
            },
            eat: function () {
                for (let j = 0; j < this.user.length; j++) {
                    this.user[j]()
                }
            }

        }

        let rose = {};
        let wml = {};

        // 制造发布者模式  hasOwnProperty
        function makePublisher(obj) {
            for (let key in publiUser) {
                // if (publiUser.hasOwnProperty(key)) {
                //     obj[key] = publiUser[key]
                // }
                // 拷贝上面的内容( use:[]) 是数组 引用类型 数据共享 需要手动添加
                if (publiUser.hasOwnProperty(key) && typeof (publiUser[key]) == 'function') {
                    obj[key] = publiUser[key]
                }

            }
            // 手动添加
            obj.user = []
        }

        // function makePublisher(obj) {
        //     console.log(JSON.stringify(publiUser), '===stringify') // 转化 引用的基础数据 函数时特殊的引用类型
        //     obj = JSON.parse(JSON.stringify(publiUser))

        // }



        // 让rose成为发布者
        makePublisher(rose);
        console.log(rose, '=========rose')
        makePublisher(wml);


        // 发布者

        let jack = {
            eat: function () {
                console.log('jack,吃饭了')
            }
        }

        let tom = {
            eat: function () {
                console.log('tom,吃饭了')
            }
        }

        rose.addUser(jack.eat)
        rose.addUser(tom.eat)

        rose.eat()
        wml.eat()
    </script> -->

    <!-- <script>
        // 多状态 发布模式
        let rose = {
            user: {
                sleep: [],
                run: []
            },

            adduser: function (fn, type) {
                if (typeof (fn) != 'function') {
                    throw '非法操作!'
                }

                if (type in this.user) {
                    this.user[type].push(fn)
                }
            },
            removeUser: function (fn, type) {
                if (!this.user.hasOwnProperty(type)) {
                    for (let i = 0; this.user[type].length; i++) {
                        if (this.user[type][i] == fn) {
                            this.user[type].splice(i, 1)
                            break;
                        }
                    }

                }
            },

            sleep: function () {
                for (let j = 0; j < this.user['sleep'].length; j++) {
                    this.user['sleep'][j]()
                }
            },
            run: function () {
                for (let k = 0; k < this.user['run'].length; k++) {
                    this.user['run'][k]()
                }
            }



        }


        // 发布者模式
        let jack = {
            sleep: function () {
                console.log('jack 睡觉了!')
            },
            run: function () {
                console.log('jack 跑步了')
            }
        }
        let tom = {
            sleep: function () {
                console.log('tom,睡觉!')
            },
            run: function () {
                console.log('tom,跑步!')
            }
        }


        // 添加
        rose.adduser(jack.sleep, 'sleep')
        rose.adduser(jack.run, 'run')

        rose.sleep()
        rose.run()

        console.log('=============')
        rose.adduser(tom.sleep, 'sleep')
        rose.adduser(tom.run, 'run')
        rose.sleep()
        rose.run()

    </script> -->
    <script>
        // 多状态 发布模式(加强版)
        let rose = {
            // 事物集合
            user: {},
            // 事件集合
            event: {},
            adduser: function (fn, type) {
                if (typeof (fn) != 'function') {
                    throw '非法操作!'
                }
                if (this.user.hasOwnProperty(type)) {
                    this.user[type].push(fn)
                } else {
                    this.user[type] = [fn]
                }


                // 初始化方法
                this.event = this.all()

            },
            removeUser: function (fn, type) {
                if (!this.user.hasOwnProperty(type)) {
                    for (let i = 0; this.user[type].length; i++) {
                        if (this.user[type][i] == fn) {
                            this.user[type].splice(i, 1)
                            break;
                        }
                    }

                }
                this.event = this.all()
            },

            all: function () {
                let obj = {}
                let that = this;
                for (let key in this.user) {
                    obj[key] = function () {
                        for (let j = 0; j < that.user[key].length; j++) {
                            that.user[key][j]()
                        }
                    }
                }
                return obj
            }

        }


        // 发布者模式
        let jack = {
            sleep: function () {
                console.log('jack 睡觉了!')
            },
            run: function () {
                console.log('jack 跑步了')
            },
            pig: function () {
                console.log('tom,pig!')
            }
        }
        let tom = {
            sleep: function () {
                console.log('tom,睡觉!')
            },
            run: function () {
                console.log('tom,跑步!')
            },
            pig: function () {
                console.log('tom,pig!')
            }
        }


        // 添加
        rose.adduser(jack.sleep, 'sleep')
        rose.adduser(jack.run, 'run')
        rose.adduser(jack.pig, 'pig')


        rose.event.run()
        rose.event.sleep()
        rose.event.pig()

        console.log('=============')
        rose.adduser(tom.sleep, 'sleep')
        rose.adduser(tom.run, 'run')
        rose.event.sleep()
        rose.event.run()

    </script>
    </script>
</body>

</html>

观察者模式实现(多个状态)


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>11-观察者模式实现01(基础版本)</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>

 步骤:
    1.提供一个发布者
    2.提供一个观察者
    3.注册观察者(建立发布者和观察者之间的联系)
    4.发布者发布信息

女神: Rose
男生 :
Jack
Tom

 思考:2个发布者
    提供一个发布者模板!

 思考:多个状态??????
<script>
    // 1.提供一个发布者模板
    var publisher = {
        user : {
            eat : [],
            sleep : []
        },
        addUser : function (fn,type) {
            var type = type || 'eat';
            if(typeof fn != 'function'){
                throw '非法操作!';
            }
            this.user[type].push(fn);
        },
        removeUser : function (fn,type) {
            var type = type || 'eat';
            for (var i = 0; i < this.user[type].length; i++) {
                if(this.user[type][i] == fn){
                    this.user[type].splice(i,1);
                }
            }
        },
        // 发布信息
        eat : function () {
            for (var i = 0; i < this.user['eat'].length; i++) {
                this.user['eat'][i]();
            }
        },
        sleep : function () {
            for (var i = 0; i < this.user['sleep'].length; i++) {
                this.user['sleep'][i]();
            }
        }
    }

    var rose = {};
    var wml = {};

    // 2.封装一个函数快速创建发布者
    function makePublisher(obj) {
        for(var key in publisher){
            // 只需要拷贝实例方法
            if(publisher.hasOwnProperty(key) && (typeof publisher[key] == 'function')){
                obj[key] = publisher[key];
            }
        }
        // 手动添加
        obj.user = {
            eat : [],
            sleep : []
        };
    }

    // 让rose成为发布者
    makePublisher(rose);
    makePublisher(wml);


    // 2.提供一个观察者
    var jack = {
        jack_eat : function () {
            console.log('邀请女神吃大餐!--Jack');
        },
        jack_sleep : function () {
            console.log('晚安!-rose!-Jack');
        }
    }

    var tom = {
        tom_eat : function () {
            console.log('邀请女神吃麻辣烫!--tom');
        },
        tom_sleep : function () {
            console.log('带你去看星星!-tom');
        }
    }

    // 3.注册观察者(建立发布者和观察者之间的联系)
    rose.addUser(jack.jack_eat,'eat');
    rose.addUser(jack.jack_sleep,'sleep');
    rose.addUser(tom.tom_sleep,'sleep');
    // 4.发布者发布信息
//    rose.eat();
    rose.sleep();

    // 5.移除观察者
    rose.removeUser(tom.tom_sleep,'sleep');

    console.log('---');
    rose.sleep();





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

观察者模式实现(优化)


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>11-观察者模式实现01(基础版本)</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>

 步骤:
    1.提供一个发布者
    2.提供一个观察者
    3.注册观察者(建立发布者和观察者之间的联系)
    4.发布者发布信息

女神: Rose
男生 :
Jack
Tom

 思考:2个发布者
    提供一个发布者模板!

 思考:多个状态??????
<script>
    // 1.提供一个发布者模板
    var publisher = {
        addUser : function (fn,type) {
            var type = type || 'eat';
            if(typeof fn != 'function'){
                throw '非法操作!';
            }

            if(this.user[type] == undefined){
                this.user[type] = [];
            }

            this.user[type].push(fn);
        },
        removeUser : function (fn,type) {
            this.publish(type,fn);
        },
        // 发布信息|| 移除观察者
        publish : function (type,fn) {
            var type = type || 'eat';
            for (var i = 0; i < this.user[type].length; i++) {
                if(typeof fn == 'function'){
                    // 移除观察
                    if(this.user[type][i] == fn){
                        this.user[type].splice(i,1);
                    }
                } else {
                    // 发布信息
                    this.user[type][i]();
                }
            }
        }
    }

    var rose = {
        // 发布信息
        eat : function () {
            this.publish('eat');
        },
        sleep : function () {
            this.publish('sleep');
        },
        run : function () {
            this.publish('run');
        }
    };
    var wml = {};

    // 2.封装一个函数快速创建发布者
    function makePublisher(obj) {
        for(var key in publisher){
            // 只需要拷贝实例方法
            if(publisher.hasOwnProperty(key) && (typeof publisher[key] == 'function')){
                obj[key] = publisher[key];
            }
        }
        // 手动添加
        obj.user = {};

    }

    // 让rose成为发布者
    makePublisher(rose);
    makePublisher(wml);


    // 2.提供一个观察者
    var jack = {
        jack_eat : function () {
            console.log('邀请女神吃大餐!--Jack');
        },
        jack_sleep : function () {
            console.log('晚安!-rose!-Jack');
        }
    }

    var tom = {
        tom_eat : function () {
            console.log('邀请女神吃麻辣烫!--tom');
        },
        tom_sleep : function () {
            console.log('带你去看星星!-tom');
        },
        tom_run : function () {
            console.log('带你去天河公园跑步!-tom');
        }
    }

    // 3.注册观察者(建立发布者和观察者之间的联系)
//    rose.addUser(jack.jack_eat,'eat');
//    rose.addUser(jack.jack_sleep,'sleep');
//    rose.addUser(tom.tom_sleep,'sleep');
    rose.addUser(tom.tom_run,'run');

    // 4.发布者发布信息
    rose.run();

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

观察者模式实现(发布者成为观察者)


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>11-观察者模式实现01(基础版本)</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>

 步骤:
    1.提供一个发布者
    2.提供一个观察者
    3.注册观察者(建立发布者和观察者之间的联系)
    4.发布者发布信息

女神: Rose
男生 :
Jack
Tom

 思考:2个发布者
    提供一个发布者模板!


<script>
    // 1.提供一个发布者模板
    var publisher = {
        addUser : function (fn,type) {
            var type = type || 'eat';
            if(typeof fn != 'function'){
                throw '非法操作!';
            }

            if(this.user[type] == undefined){
                this.user[type] = [];
            }

            this.user[type].push(fn);
        },
        removeUser : function (fn,type) {
            this.publish(type,fn);
        },
        // 发布信息|| 移除观察者
        publish : function (type,fn) {
            var type = type || 'eat';
            for (var i = 0; i < this.user[type].length; i++) {
                if(typeof fn == 'function'){
                    // 移除观察
                    if(this.user[type][i] == fn){
                        this.user[type].splice(i,1);
                    }
                } else {
                    // 发布信息
                    this.user[type][i]();
                }
            }
        }
    }

    var rose = {
        // 发布信息
        eat : function () {
            this.publish('eat');
        },
        sleep : function () {
            this.publish('sleep');
        },
        run : function () {
            this.publish('run');
        },

        // 处理发布者的状态
        rose_lol : function () {
            console.log('是我重要还是游戏重要!-Rose');
        }
    };


    // 2.封装一个函数快速创建发布者
    function makePublisher(obj) {
        for(var key in publisher){
            // 只需要拷贝实例方法
            if(publisher.hasOwnProperty(key) && (typeof publisher[key] == 'function')){
                obj[key] = publisher[key];
            }
        }
        // 手动添加
        obj.user = {};

    }

    // 让rose成为发布者
    makePublisher(rose);

    // 2.提供一个观察者
    var jack = {
        jack_eat : function () {
            console.log('邀请女神吃大餐!--Jack');
        },
        jack_sleep : function () {
            console.log('晚安!-rose!-Jack');
        },

        // 发布信息
        lol : function () {
            this.publish('lol');
        }
    }
    var tom = {
        tom_eat : function () {
            console.log('邀请女神吃麻辣烫!--tom');
        },
        tom_sleep : function () {
            console.log('带你去看星星!-tom');
        },
        tom_run : function () {
            console.log('带你去天河公园跑步!-tom');
        },
        tom_lol : function () {
            console.log('别管Rose了,来开黑把!-tom');
        }
    }

    // 让jack成为发布者
    makePublisher(jack);

    // 3.注册观察者(建立发布者和观察者之间的联系)
    jack.addUser(rose.rose_lol,'lol');
    jack.addUser(tom.tom_lol,'lol');

    // 4.发布信息
    jack.lol();
</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

web修理工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值