我学会了,观察者模式

简介: 观察者模式属于行为型模式,这个类型的设计模式总结出了 类、对象之间的经典交互方式,将类、对象的行为和使用解耦了,花式的去使用对象的行为来完成特定场景下的功能。

前言

观察者模式属于行为型模式,这个类型的设计模式总结出了 类、对象之间的经典交互方式,将类、对象的行为和使用解耦了,花式的去使用对象的行为来完成特定场景下的功能。

观察者模式

使用场景:常见的观察者模式的使用就是发布订阅,比如拍卖商品,还有过节抢火车票、飞机票、电影票之类的。这种模式比较常见,当目标对象有变化了,关注这个目标的其它人也会迅速做出相应的反应。

理解:这是一种类、对象之间的经典交互方式,将类、对象的行为和使用解耦了,这种方式有点花,但非常实用,当目标发生变化,其它关注目标的其它人就会做出相关反应。这个代码例子似乎结合了电影院买票和拍卖竞拍,原理一致,比如你用手机APP买票,如果别人选了你想要的票,那么你就不能再选这个票了,然后你就只能选其它的票。观察者需要关注这个目标,而这个目标也需要把观察者添加到候选名单中,这样目标和观察者就能相互调用,它们之间的调用是基于行为上的交互,也都封装到内部的方法中,所以能很好的将类、对象的行为和使用解耦了。

namespace action_mode_01 {

    // 票
    class Ticket {

        id: string
        position: string
        state: boolean
        user: string = ''
        price: number

        constructor(id: string, position: string) {
            this.id = id;
            this.position = position;
            this.price = ~~ (Math.random() * 1000)
            this.state = false;
        }

        // 买票,返回是否购买成功的状态
        buy() {
            if (this.isBuy()) {
                return false
            }

            this.state = true
            return this.state
        }

        isBuy() {
            return this.state
        }

    }

    // 目标:电影院卖票
    class Cinema {

        ticketBuyerList: Array<TicketBuyer> = []

        ticketList: Array<Ticket> = []

        addTicketBuyer(ticketBuyer: TicketBuyer) {
            this.ticketBuyerList.push(ticketBuyer)
        }

        constructor() {
            // 初始化十张电影票
            for (let i = 0; i < 10; i++) {
                const id = String(~~ (1000000000 * Math.random()));
                const position = String(i)
                const ticket = new Ticket(id, position)
                this.ticketList.push(ticket)
            }
        }

        startSell () {
            this.ticketBuyerList.forEach(item => {
                item.buyTicket(~~ (Math.random() * 1000))
            });

            const tempList = this.ticketList.filter(item => item.isBuy())
            if (tempList.length === this.ticketList.length) {
                console.log('======================================');
                console.log('============⭐⭐⭐⭐⭐⭐===========');
                console.log('本场电影票已卖完,买票成功的人员名单如下:');
                console.log('============⭐⭐⭐⭐⭐⭐===========');
                console.log('======================================');
                tempList.forEach(item => {
                    console.log(`票号:${item.id} 位置:${item.position} 买主是:${item.user}`)
                })

                return true
            }

            return false
        }

        sellTicket (ticketBuyer: TicketBuyer, money: number) {
            ticketBuyer.isBuy = false
            this.ticketList.forEach(item => {
                // 价格低或者本轮已经买过了
                if (money >= item.price && !ticketBuyer.isBuy) {
                    const result = item.buy()
                    // 购买成功
                    if (result) {
                        ticketBuyer.isBuy = true
                        ticketBuyer.mytickets.push(item)
                        item.user = ticketBuyer.name
                        console.log(item.user + ' 买票成功! 票号是:' + item.id + ' 位置是:' + item.position)
                    } else {
                        // 购买失败
                        console.log('票号:' + item.id + ' 位置:' + item.position + ',买主:' + item.user + ' 买票失败! ')
                    }
                }
            })
        }

    }

    // 观察者:买票黄牛
    class TicketBuyer {

        name: string
        cinema: Cinema
        isBuy: boolean = false
        mytickets: Array<Ticket> = [] 
        

        constructor (cinema: Cinema, name: string) {
            this.cinema = cinema
            this.name = name
            // this.cinema.addTicketBuyer(this) // 也可以在这里添加让目标把观察者添加进去
        }

        // 买票
        buyTicket ( money: number) {
            this.cinema.sellTicket(this,  money)
        }
    }

    // 使用
    const cinema = new Cinema()
    for (let i = 0; i < 99; i++) {
        const t = new TicketBuyer(cinema, '黄牛'+i+'号')
        cinema.addTicketBuyer(t)
    }

    let result = cinema.startSell()
    while(!result) {
        result = cinema.startSell()
    }
}
目录
相关文章
|
存储 监控 算法
深入探究Java线程池:提升并发性能的利器
在当今高度并发的应用开发中,Java线程池作为一种广泛应用的并发编程技术,提供了一种优雅且高效的线程管理方案。本文深入探究Java线程池的相关技术,涵盖其核心概念、优势、常见类型(如FixedThreadPool、CachedThreadPool、SingleThreadExecutor、ScheduledThreadPool、ForkJoinPool及WorkStealingPool)、核心参数配置、异常处理与监控方法,以及性能调优的最佳实践,帮助读者更好地理解和应用线程池,从而提升并发性能。
366 2
|
存储 自然语言处理 算法
UTF-8编码
通过阅读本篇文章,你可以了解到:UTF-8编码的规则。
1318 0
UTF-8编码
|
8天前
|
域名解析 人工智能 Linux
|
18天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
16899 62
|
16天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
2天前
|
人工智能 安全 网络安全
|
5天前
|
云安全 数据采集 人工智能
|
7天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1237 2
|
13天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2329 7
|
18天前
|
弹性计算 人工智能 API
Codex超详细入门指南(下载·安装·登录·上手,全版本覆盖,2026最新版)
建议收藏本教程,2026 全年各版本更新随时回来查阅。如果你在搭建过程中遇到任何问题,欢迎结合 阿里云工单系统 提交技术支持请求,或在 阿里云开发者社区 搜索 Codex 相关话题交流。 祝你编码愉快,效率翻倍!
3800 22