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版)

第5章 代理模式——控制对象的访问

在上一章中,我们首先简要介绍了结构型模式,并讨论了门面设计模式。我们通过UML图加深了对门面概念的理解,并且借助Python的实现展示了该模式在现实世界中的应用。最后,我们在常见问题解答部分讲解了门面模式的优点和缺点。

在本章中,我们将进一步学习结构型设计模式中的代理模式。我们首先介绍代理模式的概念,然后继续深入讨论该设计模式,并展示如何将其应用于软件程序开发。我们将提供一个示例,并通过Python v3.5实现该示例。简而言之,我们将在本章中讨论下列主题:

  • 介绍代理和代理设计模式;
  • 代理模式的UML图;
  • 代理模式的变体;
  • 利用Python v3.5代码实现的真实用例;
  • 代理模式的优点;
  • 门面模式和代理模式之间的比较;
  • 常见问答。

代理通常就是一个介于寻求方和提供方之间的中介系统。寻求方是发出请求的一方,而提供方则是根据请求提供资源的一方。在Web世界中,它相当于代理服务器。客户端(万维网中的用户)在向网站发出请求时,首先连接到代理服务器,然后向它请求诸如网页之类的资源。代理服务器在内部评估此请求,将其发送到适当的服务器,当它收到响应后,就会将响应传递给客户端。因此,代理服务器可以封装请求、保护隐私,并且非常适合在分布式架构中运行。

在设计模式的上下文中,代理是充当实际对象接口的类。对象类型可以是多样化的,例如网络连接、内存和文件中的大对象,等等。简而言之,代理就是封装实际服务对象的包装器或代理人。代理可以为其包装的对象提供附加功能,而无需更改对象的代码。代理模式的主要目的是为其他对象提供一个代理者或占位符,从而控制对实际对象的访问。

代理模式可以用于多种场景,如下所示。

  • 它能够以更简单的方式表示一个复杂的系统。例如,涉及多个复杂计算或过程的系统应该提供一个更简单的接口,让它充当客户端的代理。 ...
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