Skip to Content
Python设计模式(第2版)
book

Python设计模式(第2版)

by Posts & Telecom Press, Chetan Giridhar
February 2024
Intermediate to advanced
139 pages
1h 42m
Chinese
Packt Publishing
Content preview from Python设计模式(第2版)

第7章 命令模式——封装调用

在上一章中,我们首先介绍了行为设计模式,然后讲解了观察者的概念,并讨论了观察者设计模式。同时,还使用UML图阐释了观察者设计模式的概念,并且学习了如何借助Python实现将其应用于现实世界中。然后,我们又讨论了观察者模式的利弊,解答了与观察者模式有关的常见问题,最后对章节内容进行了总结。

在本章中,我们将讨论命令设计模式。就像观察者模式一样,命令模式业也属于行为模式的范畴。我们将首先介绍命令设计模式,并讨论如何在软件应用程序开发中应用它。同时,我们还将通过一个用例来帮助读者理解这个模式,并给出了相应的Python v3.5实现代码。

在本章中,我们将简要介绍以下主题:

  • 命令设计模式简介;
  • 命令模式及其UML图;
  • Python v3.5代码实现的真实用例;
  • 命令模式的优缺点;
  • 常见问答。

正如我们在上一章中所看到的那样,行为模式侧重于对象的响应性。它利用对象之间的交互实现更强大的功能。命令模式也是一种行为设计模式,其中对象用于封装在完成一项操作时或在触发一个事件时所需的全部信息。这些信息包括以下内容:

  • 方法名称;
  • 拥有方法的对象;
  • 方法参数的值。

让我们用一个非常简单的软件例子来理解该模式,如安装向导。通常情况下,安装向导通过多个步骤或屏幕来了解用户的偏好。因此,当用户使用向导时,他/她需要做出某些选择。通常来说,向导可以使用命令模式来实现。向导首先会启动一个名为Command的对象。用户在向导的多个步骤中指定的首选项或选项将存储在Command对象中。当用户在向导的最后一个屏幕上单击Finish按钮时,Command对象就会运行execute()方法,该方法会考察所有存储的选项并完成相应的安装过程。因此,关于选择的所有信息被封装在稍后用于采取动作的对象中。 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Python面向对象编程指南

Python面向对象编程指南

Posts & Telecom Press, Steven F. Lott
算法精讲视频课程:24篇系列讲座

算法精讲视频课程:24篇系列讲座

罗伯特·塞奇威克, 凯文·韦恩(Kevin Wayne)
人工智能技术与大数据

人工智能技术与大数据

Posts & Telecom Press, Anand Deshpande, Manish Kumar

Publisher Resources

ISBN: 9781835880043