Go Python and Design Patterns

Source: Internet
Author: User

First, create the class design pattern

Objective

What kind of programmer is a good programmer? Learn many gate programming languages, is a good programmer? In fact, learning a programming language is not a very difficult thing, and "learning" a programming language is a very difficult thing. The former "will" emphasize "can", understand the grammar, can write simple program even if the former "will", the latter "will", emphasizing "fine", obviously, light energy write "Hello World" is not the latter "will", can skillfully apply, and solve various problems with programming language, just be a true "will".

Click to read more

1. Python and design mode--Singleton mode

Bus is one of the common communication solutions for transmitting data and controlling signals between various functional parts or devices of a computer. Now assume that the following scenario: a central processing unit (CPU) through a protocol bus and a light signal connected to a signal lamp has 64 colors can be set, the central processing unit running three threads, you can control the signal, and can independently set the color of the signal. Abstract the details of the protocol (expressed in print), how to implement the thread of the signal control logic.

The addition of the line lock is undoubtedly the first thought of the method, but the control of the lock on each thread, undoubtedly increased the coupling between the modules. Below, we will use the singleton pattern in design mode to solve this problem.

What is a singleton mode? A singleton pattern is a guarantee that a class has only one instance and provides a global access point to access it. Specifically, in this case, the bus object, which is a singleton, has only one instance, and each thread accesses the bus with only one global access point, that is, the only instance.

Click to read more

2, Python and design mode--factory-related models

Presumably, you must have seen a meal system similar to the McDonald's self-help point table. On a large touchscreen display, there are three types of dishes to choose from: main meals, snacks, and drinks from Hamburg. When we choose the food we need, the payment is completed and the order is generated. Below, we use today's protagonist-the factory model-to generate the logical body of these foods.

Click to read more

3. Python and design mode-builder mode

Today's example is the last time we talked about the fast food ordering system. However, today we construct this system from an order point of view.

Click to read more

4. Python and design mode-prototype mode

If you have used a graphic design software similar to Photoshop, you must know the concept of layers. The concept of the layer, make the design, graphics modification and other operations more convenient. Designers can modify and draw the current image object, but also retain other image objects, logic clear, and can be timely feedback. In this section, you will introduce the prototype pattern with the layer as the protagonist.

Click to read more

Second, structural design patterns

1, Python and design mode--proxy mode

Proxy mode is a very high-frequency mode, which is used in many famous open source software and currently many famous Internet product background programs. Here we use an abstract simple example to illustrate the proxy pattern.

Click to read more

2. Python and design mode--decorator mode

It also mentions the fast-food ordering system, but today we only take one of these classes as the main character: the beverage category.

In addition to the basic configuration, fast food outlets to sell Coke, you can choose to add ice, if with ice, the original price to add 0.3 yuan, sell milk, you can choose to add sugar, if added sugar, the original price to add 0.5 yuan. How to solve such a problem? You can choose Adorner mode to solve this type of problem.

Click to read more

3. Python and design mode--Adapter mode

Suppose a company A and a company B need to cooperate, company a needs to access company B's personnel information, but company A and the Company B protocol interface is different, what should be handled?

Click to read more

4. Python and design mode--façade mode

The façade mode is also called the appearance pattern, which is defined as follows: requires that the external communication of a subsystem be carried out through a unified object. Façade mode provides a high-level interface that makes subsystems easier to use. The façade mode focuses on "unified objects", which is the interface that provides an access subsystem. The façade pattern has a similar place to the previously mentioned template pattern, which is the encapsulation of several methods that need to be duplicated. But in essence, it's different. The template pattern is the encapsulation of the method of the class itself, and its encapsulated method can be used alone, while the façade mode is the encapsulation of the subsystem, and the encapsulated interface is theoretically not to be used separately.

Click to read more

5. Python and design mode--combination mode

The combined pattern is also called part-the overall pattern, which is defined as follows: Grouping objects into a tree structure to represent a hierarchy of "partial" and "overall", which makes the user consistent with the use of individual objects and composite objects.

Click to read more

6. Python and design mode------Enjoy meta mode

The enjoy meta mode is defined as follows: Use shared objects to support a large number of fine-grained objects. The support sharing of a large number of fine-grained objects may involve two types of information about these objects: internal state information and external state information. Internal state information is information that can be shared, stored within the object of the privilege, and not changed as a specific environment changes; External state information is not shared. The enjoy meta mode contains only internal state information and should not contain external state information. This is something that should be considered when designing the business architecture.

Click to read more

7. Python and design mode--bridge mode

Bridge mode is also called bridging mode, which is defined as follows: Decoupling abstraction from implementation (note that the abstraction and implementation here is not the kind of relationship between abstract and implementation classes, but the relationship of a role, which needs to be distinguished here), which can be changed independently. In the example above, pen is only responsible for painting, but no shape, it does not know what to draw after all, so we call it abstract character, and shape is the concrete shape, we call it the implementation of the role. Abstract roles and implementation roles are decoupled, which means that the so-called bridge is a referential relationship between abstract classes that abstract roles and the abstract classes that implement roles.

Click to read more

Third, the Behavior class design pattern

1. Python and design mode--strategy mode

Suppose a division maintains a number of customer profiles that need to be notified when the division has a new product to launch or when it is held. There are two ways of notifying customers: SMS notification, email notification. How should the Customer Notification section of the system be designed? To solve this problem, we first construct the customer class, which includes the customer's common contact and basic information, and also includes the content to be sent.

Click to read more

2. Python and design mode--responsibility chain mode

Suppose there is such a leave system: If employees want to ask for 3 days or less (including 3 days of Leave), only the direct manager can approve it, if you want to request 3-7 days, not only the direct manager approval, the department manager needs final approval, if the absence of more than 7 days, not only the first two manager approval, also need the general manager final approval Similar systems believe that everyone has met, then how to achieve it?

Click to read more

3. Python and design mode--Command mode

It is also a ordering system (forgive the author's foodie attribute). But this time the ordering system is a restaurant's ordering system. What's the difference between a restaurant's ordering system? Guys think about it, in most hotels, when the waiter has received the customer's order, entered into the system, according to different dishes, there will be different background reaction. For example, hotels have cold dishes, hot dishes, staple food, that when the waiter will be the food input into the system, the cold dishes will print out the customer points of cold dishes, hot dishes will print out the customer points of hot dishes, staple food will print out the staple items. So how is the backend mode of this system designed?

Click to read more

4. Python and design mode--Mediator mode

There is a mobile storage management system, users have three parties: sales, warehouse manager, procurement. Demand is: Sales once the order is reached, the sales staff will be through the system of sales subsystem part of the notification warehousing subsystem, warehousing subsystem will be able to reduce the number of mobile phones, while notifying the procurement management subsystem of the current sales orders, warehousing subsystem inventory arrival threshold below, will notify the sales subsystem and procurement subsystem, and urge procurement subsystem procurement, procurement after the completion of the procurement staff will fill in the procurement subsystem, procurement subsystem will notify the sales subsystem procurement completed, and notify the warehouse subsystem to increase inventory.

From the requirements of the description, each subsystem and other subsystems have a communication, in the design of the system, if directly in a subsystem to integrate the operation of another two subsystems, one is too large, the second is not easy to expand. To solve this problem, we need to introduce a new role-mediator-to streamline the "mesh structure" to "star structure".

Click to read more

5. Python and design mode-template mode

Investment in stocks is a common way of financial management, China's more and more investors, real-time query stock demand is also growing. Today, we understand a simple design pattern through a simple stock query client: template mode.

Click to read more

6. Python and design mode--iterator mode

Today's protagonist is the iterator pattern. In Python, iterators do not use too many examples, because there are too many iterator applications in Python (in Python or many other programming languages, in fact iterators have been incorporated into commonly used libraries or packages). And at this moment, almost no one is specifically developing an iterator, but instead directly using the list, string, set, Dict, and other Python-iterated objects, or directly using the __iter__ and next functions to implement iterators.

Click to read more

7. Python and design mode-visitor mode

Suppose a pharmacy, some doctor, a drug pricing and a pharmacy administrator, they organize the workflow through a pharmacy management system. After the doctor prescribed the prescription, the drug pricing to determine whether the drug is normal, the price is correct, through the post-pharmacy administrator to open the drug treatment. How can the system be implemented? The simplest idea is to use a single if...else ... The pricing process and pharmacy management process to achieve, the problem is that the expansion is not strong, and the single is not strong, once there is a new drug to join or pricing process, the opening process some changes, will involve more changes. Today, we present a pattern to solve this type of problem: Visitor mode.

Click to read more

8. Python and design mode--viewer mode

In the façade mode, we mentioned a fire alarm. At the time, we focused on reducing code duplication through encapsulation. Today, we will implement the fire alarm again from the perspective of business process implementation.

Click to read more

9. Python and design mode-interpreter mode

In order to develop a guitar simulator that automatically recognizes sheet music, the results can be achieved by spectral sounding by the input spectrum. In addition to the audible device (assuming it is done), the most important is the ability to read and interpret the spectrum. To analyze their needs, the whole process can be divided into two parts: according to the rules of translation of the content of the spectrum, according to the content of the translation of the play. We use an interpreter model to complete this function.

Click to read more

10. Python and design mode--Memo mode

Game friends must know that most games have the ability to save progress, if a game down, forget to save the progress, then the next time only from the last progress point to start a re-hit. In general, the save progress is to exist on the persistence of the memory, in this case first to save in memory to simulate the implementation of the scenario.

Click to read more

11. Python and design mode-state mode

Elevators are everywhere around us, the elevator Control Logic Center is implemented by the elevator controller. Elevator control logic, even if the simple point design, the state into the door state, stop state and operating state, the operation is divided into open door, closed, run, stop, the process is also very complex. First of all, the open door state can not open, run, stop, stop the state can not be closed, stop, operation status can not open, close, run. To use a if...else ... Implementation, first code confusion, difficult to maintain, and the second is not easy to expand. As for the various design principles ...

So how do we do that? In the upper logic, each operation is just an operation, state switching and operation is separate, which also caused later operations and the state of "mutual coordination" of the "muddle." If the state is abstracted into a class, each state is a subclass, each state implements what operation, does not implement what operation, only in this class concrete implementation is possible.

Click to read more

Excerpt from: https://zhuanlan.zhihu.com/p/31675841

Go Python and Design Patterns

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.