Some things about Python design patterns. Can design patterns really help you solve any problems?

Table of contents

background

Design pattern definition and what it is

Design Patterns Overview

What does design pattern do?

Application scenarios

Is design pattern necessary?

Design pattern classification

1 Creational model

2 Structural pattern

3 behavioral patterns


Note: Subsequent technology sharing, immediate updates, and more timely technical information and learning technical materials will be releasedon the official account CTO Plus . Please follow the official account: CTO Plus

picture

For more technical points related to Python, please pay attention to the public account: CTO Plus’s subsequent posts. If you have any questions, please leave a message in the background to communicate.

picture

Design pattern is a summary of experience (a method of solving problems) used to solve software design problems. It provides a set of reusable solutions that can help us better organize and manage code and improve the maintainability of code. flexibility, scalability and reusability. Design patterns are the embodiment of a series of best practices and design principles accumulated during the software development process.

Everything in Python is an object. In Python, all data types are objects, including integers, floating point numbers, strings, lists, dictionaries, sets, etc. Object is the most basic data unit in Python, and each object has its own properties and methods.

Specifically, objects in Python have the following characteristics:
 

  • Objects have types: Every object has a type, and the type of the object can be obtained using the type() function.

  • Objects have properties: Each object can have its own properties, which can be accessed using the . operator

  • properties of the object. Objects can be passed as arguments: in

  • In Python, objects can be passed as parameters of functions to other functions.

  • Objects can be returned as return values: In Python, functions can return an object as a result.

Design Patterns - the basis for reusable object-oriented software.

Regarding the object-oriented nature of Python, we will introduce it in detail in the article behind the public account CTO Plus, so please pay attention.

List of articles in the Python version of Design Patterns series

"Python Design Pattern Creation Type - Singleton Pattern (Singleton)"

"Python Design Pattern Creation Type - Simple Factory Pattern (Simple Factory)"

"Python Design Pattern Creation Type - Factory Method Pattern (Factory Method)"

"Python design pattern creation type-Abstract Factory pattern (Abstract Factory)"

"Python Design Pattern Creation Type-Creator (Builder) Pattern (Builder)"

"Python Design Pattern Creation-Prototype"

"Python Design Pattern Creation Type - Object Pool Pattern (Pool)"

"Python Design Pattern Creation Type - Lazy Evaluation Mode (Lazy Evaluation)"

"Python Design Pattern Structural Type-Proxy Pattern (Proxy)"

"Python Design Pattern Structural Type-Adapter Pattern (Adapter)"

"Python Design Pattern Structural Type - Decorator Pattern (Decorator)"

"Python Design Pattern Structural Type-Composite Mode (Composite)"

"Python Design Pattern Structural Type - Facade Pattern"

"Python Design Pattern Structural Type - Flyweight Pattern (Flyweight)"

"Python Design Pattern Structural Type-Bridge Mode (Bridge)"

"Python Design Pattern Structural Type-3-tier Pattern (3-tier)"

"Python Design Pattern Structural Type - Front Controller Pattern (front controller)"

"Python Design Pattern Structural Type-MVC Pattern (mvc)"

"Python Design Patterns Behavioral-Observer Pattern (Observer)"

"Python Design Patterns Behavioral-Template Method Pattern"

"Behavioral Python Design Pattern-Strategy"

"Behavioral Python Design Pattern - Chain of Responsibility"

"Python Design Pattern Behavioral-State Pattern (State)"

"Python Design Patterns Behavioral-Iterator Pattern (Iterator)"

"Behavioral Python Design Patterns - Visitor (Visitor)"

"Behavioral Python Design Patterns - Command Mode (Command)"

"Python Design Patterns: Behavioral - Interpreter Mode (Interpreter)"

"Behavioral Python Design Patterns - Mediator (Mediator) Pattern (Mediator)"

"Behavioral Python Design Pattern - Memento Pattern (Memento)"

"Python design pattern behavioral type - catalog mode (catalog)"

"Python design pattern behavioral-method chaining pattern (chaining method)"

"Behavioral Python Design Pattern-Publish Subscribe Pattern (publish subscribe)"

"Behavioral Python Design Pattern - Registration Mode (registry)"

"Python Design Patterns Behavioral-Specification Pattern"

Similarly, design patterns have nothing to do with programming languages. I will record and summarize the design patterns of Go and C++ later.

background

In the process of software development, we often encounter some common problems, such as how to create a unique instance, how to decouple the creation and use of objects, how to achieve loose coupling between objects, etc. These problems may arise in different projects, and design patterns provide a general solution that can help us better deal with these problems.

Design pattern definition and what it is

Design pattern (Design pattern) is a set of solutions to specific problems that are repeatedly used, well-known, classified and summarized in a specific situation. It is a summary of code design experience (a way of solving problems). method). It is a template or blueprint that has been practiced and verified many times and can be widely used to solve some common problems in software design.

Design patterns are a general solution that provide a set of proven patterns and principles that can help us better organize and manage code. Design pattern is not a specific technology or tool, but an idea and methodology that can guide us on how to design and implement software systems . The purpose of using design patterns is to reuse code, make the code easier to understand by others, and ensure code reliability.

Design Patterns Overview

Design patterns can be divided into three main categories: creational patterns , structural patterns and behavioral patterns . The creational pattern focuses on the creation process of objects, the structural pattern focuses on the combination and association between objects, and the behavioral pattern focuses on the interaction and communication between objects.

What does design pattern do?

Design patterns have the following functions:

1. Provides a general solution that can solve some common problems in software design.

2. Improve the maintainability, scalability and reusability of the code, making the code easier to understand and modify.

3. Promote teamwork and communication, and improve development efficiency and quality.

4. Reduce the coupling degree of the system and make the system more flexible and reliable.

Application scenarios

Design patterns can be applied to a variety of different scenarios, including but not limited to the following:

1. When you need to create a unique instance, you can use the singleton pattern.

2. When you need to decouple the creation and use of objects, you can use the factory pattern.

3. When you need to implement a one-to-many dependency relationship between objects, you can use the observer pattern.

4. When you need to perform an operation based on different algorithms or strategies, you can use the strategy pattern.

5. The adapter pattern can be used when an incompatible interface needs to be converted into an interface expected by the client.

Is design pattern necessary?

Design patterns are not necessary to use, it is just a tool and method for solving problems. In some cases, using design patterns can better organize and manage code, improving code maintainability and reusability. But in other cases, design patterns may not be applicable or may be too complex to be worth using. Therefore, whether to use design patterns needs to be decided on a case-by-case basis.
 

Principles of design patterns

The implementation of design patterns is based on some design principles and best practices. By following these principles, software systems can be made more robust, flexible, and scalable. Design patterns are the specific implementation and application of these principles. These principles can help us better design and implement software systems. Here are some common design principles:

1. Open Close Principle

The open-closed principle means that software entities should be open to extensions and closed to modifications. When the program needs to be expanded, the original code cannot be modified to achieve a hot-swappable effect. So the summary in one sentence is: in order to make the program scalable and easy to maintain and upgrade. To achieve this effect, we need to use interfaces and abstract classes, which we will mention in the specific design later.

2. Liskov Substitution Principle

Liskov Substitution Principle LSP is one of the basic principles of object-oriented design. The Liskov Substitution Principle says that wherever a base class can appear, a subclass can definitely appear. Subclass objects can replace parent class objects without affecting the correctness of the program.

LSP is the cornerstone of inheritance and reuse. Only when the derived class can replace the base class and the function of the software unit is not affected, the base class can be truly reused, and the derived class can also add new behaviors on the basis of the base class. . The Liskov substitution principle is a complement to the "open-closed" principle. The key step in realizing the "open-closed" principle is abstraction. The inheritance relationship between base classes and subclasses is the specific implementation of abstraction, so the Liskov substitution principle is a specification for the specific steps to achieve abstraction.

3. Dependence Inversion Principle

This is the basis of the open-closed principle. High-level modules should not rely on low-level modules, they should all rely on abstractions. Specific content: It is interface programming, relying on abstraction rather than concreteness.

4. Interface Segregation Principle

Using multiple isolated interfaces is better than using a single interface. It also means reducing the coupling between classes. From here we can see that design patterns are actually a software design idea, starting from large-scale software architecture, for the convenience of upgrade and maintenance. So it appears many times above: reduce dependencies and reduce coupling.

The client should not rely on interfaces it does not need, and dependencies between classes should be established on the smallest interface.

5. Demeter Principle (Least Known Principle)

Why is it called the least known principle? That is to say: an entity should interact with other entities as little as possible so that the system functional modules are relatively independent. An object should know as little as possible about other objects and communicate only with its most immediate friends.

6. Composite Reuse Principle

The principle is to use composition/aggregation as much as possible instead of inheritance.

7. Single Responsibility Principle

A class should have only one reason for it to change.

For more technical points related to Python, please pay attention to the public account: CTO Plus’s subsequent posts. If you have any questions, please leave a message in the background to communicate.

picture

Design pattern classification

In the content outlined above, it was introduced that design patterns can be divided into three categories: creational, structural and behavioral.

At the same time, GoF has designed 23 design patterns in the book. Please see the figure below for details.

picture

1 Creational model

First, let’s introduce the creational pattern. The creational pattern is a type of design pattern that is used to create objects and the instantiation process. They provide a flexible way to create objects without exposing object creation logic and separate the creation and use of objects. Because the creation of objects consumes a lot of system resources, studying the creation phase of objects separately so that objects can be created efficiently is what we want to discuss about creational patterns.

Creational patterns exist to solve the problem of flexibility and complexity in object creation. In software development, the creation process of objects may involve complex logic and dependencies, and these details may affect the readability and maintainability of the code. Creational patterns provide a clear, extensible, and maintainable way to create objects by encapsulating the object creation process.

The following is an introduction to several common creational patterns, as follows:

1. Simple Factory Pattern (Simple Factory)

The object creation process is encapsulated through a factory class, and different specific object instances are returned according to different parameters. It hides the details of object creation. The client only needs to create objects through the factory class and does not need to care about specific implementation details.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Creation Type - Simple Factory Pattern (Simple Factory)" at the back of the public account CTO Plus.

2. Factory Method Pattern (Factory Method)

 

Define an interface for creating objects, but let subclasses decide which class to instantiate. The factory method pattern delays the creation of objects to subclasses, decoupling client code from specific classes and relying only on abstract interfaces.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Creation Type - Factory Method Pattern (Factory Method)" at the back of the public account CTO Plus.

3. Abstract Factory pattern (Abstract Factory)

 

Provides an interface for creating a series of related or interdependent objects without specifying their concrete classes. The Abstract Factory pattern provides a way to create a series of related objects by encapsulating a set of related factory methods.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Creation Type - Abstract Factory Pattern (Abstract Factory)" at the back of the public account CTO Plus.

4. Builder mode (Builder)

 

Separating the construction process of a complex object from its representation allows the same construction process to create different representations. The builder pattern breaks down the object creation process into multiple steps, and uses a mentor to control the order and combination of these steps to create different objects.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Creation Type - Creator (Builder) Pattern (Builder)" at the back of the public account CTO Plus.

5. Prototype

 

New objects are created by copying existing objects rather than by instantiating a class. The prototype pattern creates new objects by cloning existing objects, avoiding complex logic and dependencies in the object creation process.

For a detailed introduction to code examples, please pay attention to the article "Python Design Patterns - Creation-Prototype (Prototype)" at the back of the public account CTO Plus.

6. Singleton pattern (Singleton)

 

Make sure there is only one instance of a class and provide a global access point. The singleton pattern provides a way to globally access objects by restricting a class to create only one instance.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Creation Type - Singleton Pattern (Singleton)" at the back of the public account CTO Plus.

7. Object pool mode (Pool)

 

Maintain a set of reusable objects and provide an object caching and reuse mechanism. The object pool pattern creates a set of objects in advance and saves them in a pool for subsequent use.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Creation Type - Object Pool Pattern (Pool)" at the back of the public account CTO Plus.

8. Lazy Evaluation

 

Lazy calculation or lazy loading only calculates or loads when needed. Lazy evaluation mode improves performance and resource utilization by delaying the creation or calculation of objects.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Creation-Lazy Evaluation Mode (Lazy Evaluation)" at the back of the public account CTO Plus.

These creational modes have different application scenarios and functions. You can choose the appropriate mode to create objects according to specific needs. They provide a flexible, extensible, and maintainable way to create objects while also improving code readability and maintainability.

For more technical points related to Python, please pay attention to the public account: CTO Plus’s subsequent posts. If you have any questions, please leave a message in the background to communicate.

picture

2 Structural pattern

Next is an introduction to the structural pattern. After solving the problem of object creation, the composition of objects and the dependencies between objects have become the focus of developers, because how to design the structure, inheritance and dependencies of objects will affect to the maintainability of subsequent programs, the robustness and coupling of the code, etc. The design of object structure can easily reflect the level of the designer. Here are the following specific structural patterns for study, they are:

3-tier mode (3-tier)

The 3-layer model is a common software architecture model that divides a software system into three layers: presentation layer (Presentation Layer), business logic layer (Business Logic Layer) and data access layer (Data Access Layer). The function of this mode is to separate different functional modules of the system, making the system easier to maintain and expand. In application scenarios, the 3-layer model is often used to develop Web applications, in which the presentation layer is responsible for the display and interaction of the user interface, the business logic layer is responsible for processing business logic, and the data access layer is responsible for interacting with the database.

Adapter mode

The adapter pattern is a structural pattern that converts the interface of a class into another interface expected by the client, thereby allowing originally incompatible classes to work together. The role of the adapter pattern is to solve the incompatibility problem between two existing interfaces. In application scenarios, the adapter mode is often used during system upgrades or integrations to be compatible with old interfaces or third-party components.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Structural Type - Adapter Pattern (Adapter)" at the back of the public account CTO Plus.

Proxy mode (Proxy)

Proxy pattern is a structural design pattern that controls access to real objects by creating a proxy object. The proxy object and the real object implement the same interface, and the client accesses the real object through the proxy object.

For example, suppose we have an image loader through which users can load images. In order to improve the performance of loading images, we can use proxy mode. The proxy object can check whether the image already exists in the cache before loading the image. If it exists, it will directly return the image in the cache. If it does not exist, it will call the real object to load the image and store the loading result in the cache.

The proxy pattern is suitable for situations where you need to control access to real objects, extend the functionality of real objects, or access real objects remotely.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Structural Type - Proxy Pattern (Proxy)" at the back of the public account CTO Plus.

Decorator pattern (Decorator)

Decoration pattern is a structural pattern that allows you to dynamically add additional responsibilities to an object without changing the original object.

The main function of the decoration mode is to extend the functionality of objects through decorator classes without modifying existing code.

In application scenarios, the decoration mode is often used when it is necessary to dynamically add functions to objects, such as logging, performance monitoring, etc. For example, let's say we have a text editor where the user can enter text. We want to add extra features to text, such as bolding, italics, and underlining. If you add these functions directly to the text object, the code of the text object will become complex and difficult to maintain.

Using the decorator pattern, we can create a decorator class to wrap the text object and add extra functionality in the decorator class. For example, you can create a bold decorator class, an italic decorator class, and an underline decorator class to add bold, italics, and underline to text respectively. Clients can selectively combine these decorator classes to achieve different combinations of functionality.

In short, the decorator pattern is suitable for situations where you need to dynamically add additional responsibilities to an object, extend the functionality of the object, or dynamically combine the functionality of the object.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Structural Type - Decorator Pattern (Decorator)" at the back of the public account CTO Plus.

Bridge mode (Bridge)

Bridge pattern is a structural design pattern that separates the abstract part and the implementation part so that they can change independently. The bridge pattern connects the abstract part and the implementation part by creating a bridge interface, and defines the methods of the abstract part and the implementation part in the bridge interface.

The purpose of the bridge pattern is to decouple abstraction and implementation so that they can be extended independently. In application scenarios, the bridge mode is often used in situations where multi-dimensional changes are required . For example, graphical interfaces under different operating systems, different brands of mobile phones and software. Suppose we have a drawing program that can draw different types of shapes, such as circles, rectangles, and triangles. We want to be able to choose different colors such as red, green and blue while drawing the graph. If you add color properties directly to the graphics class, the code of the graphics class will become complex and difficult to maintain.

Using the bridge pattern, we can create a color interface and a graphics interface, and define the methods of the abstract part and the implementation part in the bridge interface. Then, we can create different color implementation classes and graphics implementation classes, and dynamically select different colors and graphics for combination in the client.

In short, the bridge pattern is suitable for situations where there are multiple independently changing dimensions, the abstract part and the implementation part need to be dynamically selected at runtime, or expansion in multiple dimensions is required.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Structural Type-Bridge Mode (Bridge, Multi-Dimension)" at the back of the public account CTO Plus.

Composite mode

The composition pattern is a structural design pattern that combines objects into a tree structure to represent a "part-whole" hierarchy. The composition pattern allows clients to uniformly handle single objects and composite objects.

The purpose of the composition pattern is to provide consistency in the use of individual objects and composite objects. In application scenarios, the combination mode is often used to process tree-structured data, such as file systems, menus, organizational structures, etc.

For example, let's say we have a file system that contains files and folders. Folders can contain files and other folders. We hope to be able to perform unified operations on the file system, such as traversing the file system, calculating the total size of the file system, etc.

Using the Composite pattern, we can create an abstract file system object containing files and folders. Both files and folders are subclasses of file system objects. Folders can contain other file system objects, forming a tree structure. Clients can handle files and folders uniformly without having to write different code for them.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Structural Type-Composite Pattern (Composite)" at the back of the public account CTO Plus.

Facade

Facade pattern is a structural design pattern that provides a unified interface for accessing a set of interfaces in a subsystem. The appearance pattern hides the complexity of the subsystem behind a simple interface. The client only needs to access the subsystem through the appearance object without directly interacting with the subsystem.

The main role of the appearance pattern is to simplify the interaction between the client and the subsystem. The appearance object provides a unified interface, hiding the complexity of the subsystem, making it easier for clients to use the subsystem.

For example, suppose we have a file reader through which users can read different types of files. The reader needs to select different reading strategies based on the type of file. For example, text files use the text reading strategy, and image files use the image reading strategy. If the client interacts directly with the read strategy, the client code will become complex and difficult to maintain.

Using the Appearance pattern, we can create a file reader facade object that hides the complexity of the read strategy within the facade object. The client only needs to read the file through the appearance object and does not need to interact directly with the read strategy. The appearance object selects an appropriate reading strategy based on the file type and returns the reading results to the client.

In short, the appearance pattern is suitable for situations where it is necessary to simplify the interaction between the client and the subsystem, encapsulate the interface of the subsystem, and decouple the dependencies between the client and the subsystem.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Structural Type - Facade Pattern (Facade)" at the back of the public account CTO Plus.

Flyweight mode

Flyweight pattern is a structural design pattern that reduces memory usage and improves performance through shared objects. The flyweight pattern divides objects into shareable internal states and non-shareable external states, and reduces the number of objects by sharing internal states.

The main function of flyweight mode is to reduce memory usage and improve performance. By sharing internal state, the number of objects can be reduced, thereby reducing memory usage. At the same time, shared objects can reduce the creation and destruction of objects and improve performance.

For example, suppose we have a text editor where users can insert different images. To save memory and improve performance, we want to share the same images. Creating an instance of each image directly would result in excessive memory usage.

Using the flyweight pattern, we can create an image factory that is responsible for creating and managing image instances. When the user needs to insert a picture, we first check whether the same picture instance already exists in the picture factory. If it exists, return the shared instance. If it does not exist, create a new instance and save it to the picture factory.

In short, the flyweight pattern is suitable for situations where a large number of similar objects need to be created, the cost of creating and destroying objects is very high, or the state of the object can be divided into internal state and external state.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Structural Type - Flyweight Pattern (Flyweight)" at the back of the public account CTO Plus.

Front controller pattern (front controller)

Front Controller is a design pattern used to centrally handle requests and control the flow of an application. It provides a single entry point for handling all requests and coordinates other components to complete request processing and responses.

The role of the front controller pattern is to provide a unified entry point for handling requests and controlling the flow of the application. It can centrally handle common processing logic such as request verification, identity authentication, and logging, thereby improving code reusability and maintainability. At the same time, it can also coordinate other components to complete request processing and response, making the system more flexible and scalable.

MVC pattern (mvc)

The MVC pattern (Model-View-Controller) is a software architecture pattern used to separate the logic, data and user interface of an application. It divides the application into three main parts: Model, View and Controller. The model is responsible for handling data logic, the view is responsible for displaying the user interface, and the controller is responsible for handling user input and controlling the flow of the application.

The role of the MVC pattern is to separate the logic, data and user interface of the application, thereby improving the flexibility and maintainability of the system. By dividing the application into three main parts, the MVC pattern enables modular design and development so that the code in different parts can be modified and extended independently.

In actual software development, we can choose appropriate design patterns according to specific needs and scenarios to improve code readability, maintainability and performance.

For more technical points related to Python, please pay attention to the public account: CTO Plus’s subsequent posts. If you have any questions, please leave a message in the background to communicate.

picture

3 behavioral patterns

Finally, we come to the behavioral pattern of objects. The behavioral pattern is a design pattern that focuses on communication and interaction between objects. They focus primarily on the interaction between objects and how to assign responsibilities and actions to different objects.

After the object creation and object structure problems are solved, only the object's behavior problem remains. If the object's behavior is well designed, then the object's behavior will be clearer, and the collaboration efficiency between them will be improved. The following are several specific behavioral patterns that can be studied. They are:

Observer pattern (Observer)

The Observer pattern is a behavioral design pattern that defines a one-to-many dependency relationship that allows multiple observer objects to monitor a subject object at the same time. When the topic object changes, it automatically notifies all observer objects (typical publish and subscribe).

The role of the observer pattern is to achieve loose coupling between objects and make the dependency relationship between subject objects and observer objects dynamic and flexible. The subject object only needs to maintain a list of observers and does not need to care about specific observer objects.

Application scenarios of the observer pattern include:

1. When changes in one object need to be notified to other objects at the same time, the observer pattern can be used. For example, when an order status changes, users, inventory management systems, and logistics systems need to be notified.

2. When the state change of an object needs to trigger the action of other objects, the observer pattern can be used. For example, when a button is clicked, it needs to trigger corresponding actions on other objects.

3. When an object needs to notify other objects of its state changes, it can use the observer pattern. For example, when a news publisher publishes a news item, all subscribers need to be notified.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Behavioral Type - Observer Pattern (Observer)" at the back of the public account CTO Plus.

State mode

The State pattern is a behavioral design pattern that allows an object to change its behavior when its internal state changes. The state pattern encapsulates the behavior of objects in different state classes, and objects have different behaviors in different states.

The function of the state mode is to convert complex conditional judgment statements into a set of state classes, allowing objects to automatically switch behaviors according to changes in internal state. The state pattern decouples state changes and behavior implementation, making the code clearer and easier to maintain.

Application scenarios of state mode include:

1. The state pattern can be used when the behavior of an object depends on its state and the behavior needs to change based on the state at runtime. For example, when the status of an order changes, the way the order is processed needs to be changed.

2. When an object has multiple states and there are transitions between states, the state pattern can be used. For example, when a game character has multiple states (normal, injured, dead) and the states can be converted to each other.

3. When the behavior of an object contains a large number of conditional judgment statements, the state mode can be used. The state pattern encapsulates each conditional statement in a different state class, making the code clearer and easier to understand.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Behavioral Type - State Pattern (State)" at the back of the public account CTO Plus.

Strategy

Strategy pattern is a behavioral design pattern that defines a set of algorithms and encapsulates each algorithm in an independent strategy class. The client can choose different policy classes to execute different algorithms as needed.

The role of the strategy pattern is to separate the implementation and use of the algorithm so that the algorithm can change independently of changes in the client. Strategy pattern can improve the flexibility and maintainability of code, while also reducing code duplication.

Application scenarios of the strategy pattern include:

1. When a system needs to support multiple algorithms and needs to dynamically select algorithms at runtime, the strategy pattern can be used. For example, when a sorting algorithm has multiple implementations and needs to be chosen at runtime.

2. The strategy pattern can be used when an object has multiple behaviors and the behaviors can be replaced with each other. For example, when a payment method can have multiple implementations and needs to be selected at runtime.

3. When a system needs to use different algorithms on different platforms or environments, the strategy pattern can be used. For example, when an image processing software needs to use different rendering algorithms on Windows and Mac platforms.

For a detailed introduction to code examples, please pay attention to the article "Python Design Patterns Behavioral - Strategy Pattern (Strategy)" at the back of the public account CTO Plus.

Chain of Responsibility (Chain of Responsibility) model

The chain of responsibility pattern is a behavioral design pattern that decouples the sender and receiver of the request so that multiple objects have the opportunity to handle the request. The Chain of Responsibility pattern organizes receivers into a chain-like structure and passes requests along the chain until a receiver handles the request.

The role of the chain of responsibility pattern is to decouple the sender and receiver of the request so that the request can be passed along the chain until a receiver handles the request. The chain of responsibility model can dynamically change the structure and processing order of the chain, improving the flexibility and scalability of the system.

Application scenarios of the chain of responsibility model include:

1. When a request requires multiple objects to process, and each object handles the request differently, the chain of responsibility pattern can be used. For example, when an order needs to be reviewed by multiple departments, each department's review method is different.

2. When a request needs to be processed in a certain order, the chain of responsibility model can be used. For example, when a request needs to be processed according to a certain priority.

3. When the sender and receiver of a request need to be decoupled, the chain of responsibility pattern can be used. For example, when the sender of a request does not need to know who the recipient of the request is.

For detailed code example introduction, please pay attention to the article "Behavioral Python Design Pattern - Chain of Responsibility Pattern (Chain of Responsibility)" at the back of the public account CTO Plus.

Command mode (Command)

The command pattern is a behavioral design pattern that encapsulates requests into an object so that other objects can be parameterized with different requests. The command pattern allows decoupling the sender and receiver of a request.

The role of the command pattern is to decouple the sender and receiver of the request so that the request can be parameterized and passed. The command mode can encapsulate the sender and receiver of the request in different objects, making the system more flexible and scalable.

Application scenarios of command mode include:

1. When the sender and receiver of a request need to be decoupled, the command mode can be used. For example, when the sender of a request does not need to know who the recipient of the request is.

2. When you need to encapsulate the sender and receiver of the request in different objects, and need to support undo and redo operations, you can use the command mode. For example, when a text editor needs to support undo and redo operations.

3. When you need to support functions such as command queues, request logs, and transactions, you can use the command mode. For example, when an e-commerce platform needs to record user operation logs.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Behavioral Type - Command Mode (Command)" behind the public account CTO Plus.

Visitor mode

Visitor pattern (Visitor) is a behavioral design pattern used to separate algorithms from data structures, thereby improving the flexibility and scalability of the system. It defines an accessor class for accessing and operating on elements in the data structure. The visitor pattern can add new operations and algorithms without modifying the data structure. At the same time, it can also separate the traversal and operation logic of the data structure, making the system more flexible and maintainable.

Visitor mode is suitable for the following scenarios:

1. When the elements in a data structure need to perform different operations, you can use the visitor pattern. By defining different visitor classes, different operations can be performed on elements in the data structure without modifying the data structure itself.

2. The visitor pattern can be used when the combination of elements and operations of a data structure may change. By defining new visitor classes, new operations and algorithms can be added without modifying the data structure itself.

3. When the combination of elements and operations of a data structure is very complex, the visitor pattern can be used. By separating the traversal and operation logic of the data structure, the code can be made clearer and more maintainable.

For detailed code example introduction, please pay attention to the article "Behavioral Python Design Pattern - Visitor (Visitor) Mode (Visitor)" at the back of the public account CTO Plus.

Mediator (Mediator) Pattern (Mediator)

The mediator pattern is a behavioral design pattern that encapsulates the interaction between objects into a mediator object, so that the objects do not need to communicate directly with each other. The mediator pattern can reduce the coupling between objects and improve the flexibility and maintainability of the system.

Application scenarios of the mediator pattern include:

1. When there are complex interactions between objects in a system, the mediator pattern can be used. For example, when multiple components in a GUI interface need to communicate with each other.

2. When the interaction between objects in a system needs to be reused or extended, the mediator pattern can be used. For example, when multiple subsystems in a system need to share certain information.

3. When the interactions between objects in a system need to be managed centrally, the mediator pattern can be used. For example, when multiple objects in a system need to coordinate with each other.

For detailed code example introduction, please pay attention to the article "Behavioral Python Design Pattern - Mediator (Mediator) Pattern (Mediator)" at the back of the public account CTO Plus.

For more technical points related to Python, please pay attention to the public account: CTO Plus’s subsequent posts. If you have any questions, please leave a message in the background to communicate.

picture

Memento mode

The memo pattern is a behavioral design pattern that captures the internal state of an object and restores the object's state when needed without destroying the object's encapsulation. The memo mode can provide a snapshot function of an object, allowing the object to switch between different states.

Application scenarios of memo mode include:

1. When an object needs to save and restore its internal state, the memo pattern can be used. For example, when a text editor needs to save and restore the user's editing history.

2. When the state changes of an object need to be recorded and rolled back, the memo mode can be used. For example, when a game needs to save and restore a player's game progress.

3. When the state changes of an object need to be observed and notified to other objects, the memo pattern can be used. For example, when multiple objects in a system need to observe and notify state changes of an object.

For detailed code examples, please pay attention to the article "Behavioral Python Design Pattern - Memento Pattern (Memento)" at the back of the public account CTO Plus.

Iterator pattern (Iterator)

The iterator pattern is a behavioral design pattern that provides a unified way to access various elements in a container object without exposing the internal structure of the container. The iterator pattern can separate container objects and traversal algorithms, thereby improving the flexibility and maintainability of the system.

Application scenarios of the iterator pattern include:

1. When a container object needs to provide a unified way to access its elements, the iterator pattern can be used. For example, when a collection class needs to provide a unified way to traverse.

2. When the internal structure of a container object changes and you do not want to affect its traversal algorithm, you can use the iterator pattern. For example, when the internal structure of a collection class changes from an array to a linked list.

3. When a container object needs to support multiple traversal methods, the iterator pattern can be used. For example, when a collection class needs to support forward traversal and reverse traversal.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Behavioral Type - Iterator Pattern (Iterator)" at the back of the public account CTO Plus.

Interpreter mode (Interpreter)

The interpreter pattern is a behavioral design pattern that defines the grammar of a language and uses an interpreter to interpret expressions in the language. The interpreter pattern can decompose a complex problem into simple expressions, thereby improving the flexibility and scalability of the system.

Application scenarios of the interpreter mode include:

1. The interpreter pattern can be used when a problem can be described by the grammar of a language. For example, when a calculator needs to support complex mathematical expressions.

2. Interpreter pattern can be used when a problem can be broken down into simple expressions and can be solved by combining these expressions. For example, when a text parser needs to parse complex text formats.

3. The interpreter mode can be used when the solution to a problem needs to be customized according to different language grammars. For example, when a translator needs to translate text according to different languages.

For a detailed introduction to code examples, please pay attention to the article "Python Design Patterns Behavioral - Interpreter Mode (Interpreter)" at the back of the public account CTO Plus.

Template Method

The template method is a behavioral design pattern that defines the skeleton of an algorithm and defers the specific implementation of some steps to subclasses. The template method can provide a unified algorithm framework, thereby improving the flexibility and maintainability of the system.

Application scenarios for template methods include:

1. When the skeleton of an algorithm has been determined, but the specific implementation of some steps may change, the template method can be used. For example, when the comparison rules of a sorting algorithm can change according to different needs.

2. When different steps of an algorithm require different implementations, the template method can be used. For example, when a text processor needs to support different file formats.

3. When different steps of an algorithm need to work together, the template method can be used. For example, when the level design of a game requires collaborative designers, programmers and art designers to complete.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Behavioral-Template Method Pattern" at the back of the public account CTO Plus.

Catalog mode (Catalog)

Catalog pattern (Catalog) is a software design pattern used to manage and organize a large number of objects. It provides a way to quickly find and access objects by classifying and organizing objects according to certain rules. The directory mode can improve the performance and maintainability of the system.

Directory mode is suitable for the following scenarios:

1. When there are a large number of objects in the system and need to be classified and organized according to certain rules, the directory mode can be used. For example, products on an e-commerce website can be classified and organized by category, brand, price, etc.

2. Directory mode can be used when the system needs to provide a quick way to find and access objects. By using directory mode, you avoid traversing the entire collection of objects to find and access objects.

3. When the system needs to support dynamic addition and deletion of objects, directory mode can be used. By using the directory pattern, dynamic management and organization of objects can be achieved.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Behavioral Type - Catalog Mode (catalog)" at the back of the public account CTO Plus.

Chaining Method

Chaining Method is a programming technique used to continuously call multiple methods. It implements method chaining by returning the object itself in each method.

The method chain pattern is used to simplify writing and reading code. By using the method chain pattern, multiple method calls can be chained together, thereby reducing code duplication and improving code readability.

The method chain pattern is suitable for the following scenarios:

1. When an object needs to call multiple methods continuously, the method chain pattern can be used. For example, a database query object can set query conditions, sorting methods, and paging parameters through method chains.

2. When an object needs to provide a concise interface to operate and modify its internal state, the method chain pattern can be used. By using the method chain pattern, multiple operations and state-modifying methods can be chained together to provide a concise interface.

3. When you need to perform multiple operations on an object and want to write and read the code more clearly and concisely, you can use the method chain pattern.

For detailed code example introduction, please pay attention to the article "Python Design Pattern Behavioral-Method Chaining Pattern (chaining method)" at the back of the public account CTO Plus.

Publish-Subscribe model (Publish-Subscribe)

The publish-subscribe pattern (Publish-Subscribe) is a messaging pattern used to achieve loosely coupled message communication. It decouples the sender (publisher) and receiver (subscriber) of the message and delivers the message through an intermediary (message queue). The publish-subscribe model can improve the flexibility and scalability of the system.

The publish-subscribe model is suitable for the following scenarios:

1. When there are multiple modules or components in the system and message delivery is required, the publish-subscribe model can be used. By using the publish-subscribe pattern, decoupling between modules or components can be achieved, thereby improving the flexibility and scalability of the system.

2. When the system needs to support dynamic addition and deletion of message receivers, the publish-subscribe model can be used. By using the publish-subscribe model, dynamic message subscription and unsubscription can be achieved.

3. When the system needs to support one-to-many messaging, the publish-subscribe model can be used. By using the publish-subscribe pattern, messages can be sent to multiple receivers, thereby achieving one-to-many messaging.

For detailed code example introduction, please pay attention to the article "Behavioral Python Design Pattern - Publish Subscribe Model (publish subscribe)" at the back of the public account CTO Plus.

Registration mode (Registry)

Registration pattern (Registry) is a software design pattern used to manage and access global objects. It provides a unified access method by registering global objects into a central registry. The registration mode can simplify code writing and improve the maintainability of the system.

Registration mode is suitable for the following scenarios:

1. When there are multiple global objects in the system and need to be managed and accessed uniformly, the registration mode can be used. By using registration mode, global objects can be registered into a central registry, providing a unified way to access them.

2. When the system needs to support dynamic addition and deletion of global objects, the registration mode can be used. By using the registration mode, dynamic management and access of global objects can be achieved.

3. When the system needs to provide a simple interface to operate and access global objects, the registration mode can be used. By using the registration pattern, multiple operations and methods of accessing global objects can be unified into one interface.

For a detailed introduction to code examples, please pay attention to the article "Behavioral Python Design Pattern - Registration Mode (registry)" at the back of the public account CTO Plus.

Specification mode

Specification pattern is a software design pattern used to describe certain attributes or conditions of objects. It abstracts the properties or conditions of an object into specifications and provides a way to judge whether the object meets the specifications. By using the specification pattern, the attributes or conditions of objects can be separated from specific business logic, improving the maintainability and scalability of the system.

Specification mode is suitable for the following scenarios:

1. When the system needs to describe certain attributes or conditions of an object and needs to make judgments based on these attributes or conditions, the specification mode can be used. For example, an e-commerce website needs to determine whether a product can be purchased based on its price, inventory and other attributes.

2. When the system needs to separate the properties or conditions of objects from specific business logic, the specification mode can be used. By using the specification pattern, the properties or conditions of an object can be abstracted into specifications, thereby improving the maintainability and scalability of the system.

3. When the system needs to support dynamic combination and judgment of attributes or conditions of objects, the specification mode can be used. By using specification mode, dynamic combination and judgment of specifications can be achieved.

For a detailed introduction to code examples, please pay attention to the article "Python Design Patterns Behavioral - Specification" at the back of the public account CTO Plus.

For more technical points related to Python, please pay attention to the public account: CTO Plus’s subsequent posts. If you have any questions, please leave a message in the background to communicate.

picture

At this point, the design patterns related to Python have been popularized. In the following articles, we will demonstrate them one by one using code examples.

Python column
https://blog.csdn.net/zhouruifu2015/category_5742543

For more exciting news, follow my official account and learn and grow together.

picture

Python column
https://blog.csdn.net/zhouruifu2015/category_5742543


More information · Search the WeChat public account [ CTO Plus ] and follow it to get more information. Let’s learn and communicate together.

For a description of the public account, visit the following link


For more exciting news, follow my official account and learn and grow together.

About Articulate "Be a porter of knowledge and technology. Be a lifelong learning enthusiast. Be a technical circle with depth and breadth." I have always wanted to develop skills in the professional field icon-default.png?t=N7T8https://mp.weixin.qq. com/s?__biz=MzIyMzQ5MTY4OQ==&mid=2247484278&idx=1&sn=2b774f789b4c7a2ccf10e465a1b9def6&chksm=e81c2070df6ba966026fd7851efa824b5e2704e3fd34e 76228ca4ce64d93f7964cd4abe60f2b#rd

Standard Library Series-Recommended Reading:

Recommended
reading:

Guess you like

Origin blog.csdn.net/zhouruifu2015/article/details/133387810