Object Oriented Python 简明教程
Python Design Pattern
Overview
现代软件开发需要满足复杂业务需求。它还需要考虑以下因素,例如将来的可扩展性和可维护性。软件系统的好设计对于实现这些目标至关重要。设计模式在这样的系统中起着重要作用。
Modern software development needs to address complex business requirements. It also needs to take into account factors such as future extensibility and maintainability. A good design of a software system is vital to accomplish these goals. Design patterns play an important role in such systems.
为了理解设计模式,让我们考虑以下示例 -
To understand design pattern, let’s consider below example −
-
Every car’s design follows a basic design pattern, four wheels, steering wheel, the core drive system like accelerator-break-clutch, etc.
因此,所有反复构建/生成的物品必然在其设计中遵循一种模式,比如汽车、自行车、比萨饼、ATM 机,甚至是你的沙发床。
So, all things repeatedly built/ produced, shall inevitably follow a pattern in its design.. it cars, bicycle, pizza, atm machines, whatever…even your sofa bed.
几乎已成为编码软件中的某种逻辑/机制/技术标准的方法的设计,因此被称为或研究为软件设计模式。
Designs that have almost become standard way of coding some logic/mechanism/technique in software, hence come to be known as or studied as, Software Design Patterns.
Why is Design Pattern Important?
使用设计模式的好处如下−
Benefits of using Design Patterns are −
-
Helps you to solve common design problems through a proven approach.
-
No ambiguity in the understanding as they are well documented.
-
Reduce the overall development time.
-
Helps you deal with future extensions and modifications with more ease than otherwise.
-
May reduce errors in the system since they are proven solutions to common problems.
Classification of Design Patterns
GoF(四人帮)设计模式分为三类,即创建型、结构型和行为型。
The GoF (Gang of Four) design patterns are classified into three categories namely creational, structural and behavioral.
Creational Patterns
创建型设计模式将对象创建逻辑与系统其他部分分离开来。创建型模式替代你创建对象,为你创建它们。创建型模式包括抽象工厂、生成器、工厂方法、原型和单例。
Creational design patterns separate the object creation logic from the rest of the system. Instead of you creating objects, creational patterns creates them for you. The creational patterns include Abstract Factory, Builder, Factory Method, Prototype and Singleton.
由于语言的动态特性,Python 中通常不使用创建型模式。此外,语言本身为我们提供了创建的所需灵活性,以足够优雅的方式,我们很少需要在顶层实现任何东西,如单例或工厂。
Creational Patterns are not commonly used in Python because of the dynamic nature of the language. Also language itself provide us with all the flexibility we need to create in a sufficient elegant fashion, we rarely need to implement anything on top, like singleton or Factory.
此外,这些模式提供了一种在隐藏创建逻辑的情况下创建对象的方式,而不是直接使用 new 运算符实例化对象。
Also these patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using a new operator.
Structural Patterns
有时,你不必从头开始,而是需要使用一组现有的类来构建更大的结构。这就是结构类模式使用继承来构建新结构的地方。结构对象模式使用组合/聚合来获得新功能。适配器、桥接、复合、装饰器、外观、享元和代理是结构模式。它们提供了组织类层次结构的最佳方式。
Sometimes instead of starting from scratch, you need to build larger structures by using an existing set of classes. That’s where structural class patterns use inheritance to build a new structure. Structural object patterns use composition/ aggregation to obtain a new functionality. Adapter, Bridge, Composite, Decorator, Façade, Flyweight and Proxy are Structural Patterns. They offers best ways to organize class hierarchy.
Behavioral Patterns
行为模式提供了处理对象之间通信的最佳方式。属于此类别的模式有:访问者、职责链、命令、解释器、迭代器、中介者、备忘录、观察者、状态、策略和模板方法是行为模式。
Behavioral patterns offers best ways of handling communication between objects. Patterns comes under this categories are: Visitor, Chain of responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy and Template method are Behavioral Patterns.
因为它们表示系统的行为,所以通常用于描述软件系统的功能。
Because they represent the behavior of a system, they are used generally to describe the functionality of software systems.
Commonly used Design Patterns
Singleton
它是所有设计模式中最有争议和最著名的模式之一。它用于过度面向对象语言,并且是传统面向对象编程的重要组成部分。
It is one of the most controversial and famous of all design patterns. It is used in overly object-oriented languages, and is a vital part of traditional object-oriented programming.
单例模式用于:
The Singleton pattern is used for,
-
When logging needs to be implemented. The logger instance is shared by all the components of the system.
-
The configuration files is using this because cache of information needs to be maintained and shared by all the various components in the system.
-
Managing a connection to a database.
以下是 UML 图表,
Here is the UML diagram,

class Logger(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_logger'):
cls._logger = super(Logger, cls).__new__(cls, *args, **kwargs)
return cls._logger
此示例中,Logger 为单例。
In this example, Logger is a Singleton.
在调用 new 时,它会构造该类的某个新实例。当覆盖它时,我们首先检查我们的单例实例是否已创建。如果没有,我们使用超级调用创建它。因此,每当我们调用 Logger 上的构造函数时,我们始终会获得完全相同的实例。
When new is called, it normally constructs a new instance of that class. When we override it, we first check if our singleton instance has been created or not. If not, we create it using a super call. Thus, whenever we call the constructor on Logger, we always get the exact same instance.
>>>
>>> obj1 = Logger()
>>> obj2 = Logger()
>>> obj1 == obj2
True
>>>
>>> obj1
<__main__.Logger object at 0x03224090>
>>> obj2
<__main__.Logger object at 0x03224090>