Skip to Content
Python高级编程(第2版)
book

Python高级编程(第2版)

by Posts & Telecom Press, Michał Jaworski, Tarek Ziadé
February 2024
Intermediate to advanced
423 pages
6h 9m
Chinese
Packt Publishing
Content preview from Python高级编程(第2版)

第14章 有用的设计模式

针对软件设计的常见问题,设计模式是可复用的且有点语言相关的解决方案。关于这个主题的最流行的书是Design Patterns: Elements of Reusable Object-Oriented Software,这本书由Gamma、Helm、Johnson和Vlissides编写,它们也被称为四人组(Gang of Four)或GoF。这本书是这个领域中的重要著作,它收录了23种设计模式,并使用SmallTalk和C++编写了示例。

在设计应用程序的代码时,这些模式有助于解决常见问题。所有开发人员对它们都似曾相识,因为它们描述了已验证的开发范例。但是在学习这些模式时应该考虑使用的语言,因为其中一些在某些语言中没有意义或者语言中已经内置了。

本章介绍了Python中最有用的以及最值得大家讨论的模式,以及实现示例。以下3个部分对应于GoF定义的设计模式类别。

  • 创建型模式(creational patterns):这些模式用于生成具有特定行为的对象。
  • 结构型模式(structural patterns):这些模式有助于为特定用例构建代码。
  • 行为模式(behavioral patterns):这些模式有助于分配责任和封装行为。

创建型模式处理对象实例化机制。这样的模式可以定义如何创建对象实例或者甚至如何构造类的方式。

这些是编译型语言(如C或C ++)中非常重要的模式,因为在运行时难以生成需要的类型。

但是在运行时创建新类型在Python中是相当简单的。使用内置的type函数可以通过代码定义一个新类型的对象如下:

>>> MyType = type('MyType', (object,), {'a': 1})
>>> ob = ...
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

Hadoop实际解决方案手册

Hadoop实际解决方案手册

Posts & Telecom Press, JONATHAN OWENS, Lentz Jon, Femiano Brian
TensorFlow机器学习

TensorFlow机器学习

Posts & Telecom Press, Quan Hua, Shams Ul Azeem, Saif Ahmed
Python和NLTK实现自然语言处理

Python和NLTK实现自然语言处理

Posts & Telecom Press, Nitin Hardeniya
Kafka权威指南(第2版)

Kafka权威指南(第2版)

Gwen Shapira, Todd Palino, Rajini Sivaram, Krit Petty

Publisher Resources

ISBN: 9781835887745