Python, "Big talk design mode", code implementation

Source: Internet
Author: User
Tags python list

"Big talk design mode" Python version of Code implementation

Last week, the "Big Talk design mode" read, the object-oriented technology has a new understanding of a C under the code more, and occasionally use some scripting language to write scripts, it is very eye-broadening. "Big Talk design Mode" code is written in C #, and in my contact with the object-oriented language, only for C + + and Python to understand, in order to deepen the understanding of the various patterns, I downloaded a C + + version of the source code, and according to their own understanding of reading this book side to hands-on practice C + + source code, At the same time it was rewritten as a Python code, it is a three-eagle arrow.

Since the purpose of this code is to show each design pattern rather than complete a specific complex task, based on the C + + version of the rewrite, examples of the material and "Big talk design mode" basically the same, coupled with limited personal level, so these Python version of the code is relatively simple to write, although can run is not fake, but there are inevitably bugs , and the implementation is not necessarily optimal, C + + flavor is relatively strong and not enough pythonic, but also please master. But I try to put something more or less pythonic in the "Code features" section of each pattern, and this "code feature" is more than just pythonic.

Use the Python version of 2.6.

Drawing is also excerpted from the "Big Talk design mode", so it is a C # style UML class diagram, in order to facilitate the layout has been reduced.

  

First, simple Factory mode

Pattern Features: The factory produces classes of different functions according to conditions.

Program Example: Arithmetic calculator, according to the user's input produces the corresponding operation class, uses this operation class to handle the concrete operation.

Code Features: Switch...case ... The branch uses a dictionary instead.

Use the exception mechanism to process a divisor of 0.

Simple Factory mode

Second, the Strategy model

Pattern Features: Define the algorithm family and encapsulate them separately, and they can be replaced with each other without affecting the client.

Program Example: Store cashier software, need to be based on different sales strategy way to charge

Code features: Unlike in the same example 1, the dictionary is used here to avoid pitfalls where the keyword does not cause bugs in the dictionary.

Policy Mode

Three, decorative mode

Pattern Features: Add additional responsibilities dynamically to objects

Program Example: show a person to dress the process of one piece.

Code Features: None

Decoration Mode

Iv. Proxy Mode

Pattern Features: Provides a proxy for other objects to control access to this object.

Example of a program: The characteristic description of the same pattern.

Code Features: None

Proxy Mode

Five, factory method mode

Pattern feature: Defines an interface for creating objects, letting subclasses decide which class to instantiate. This causes the instantiation of a class to be deferred to its subclasses.

Program examples: The base class Lei Feng class, derived from the student class and volunteer class, by the two seed classes to complete the "learn Lei Feng" work. The creation of subclasses is done by the corresponding subclasses of the Lei Feng factory.

Code Features: None

Factory Method Mode

VI. Prototype Model

Pattern Features: Use prototype instances to specify the kind of objects that are created, and create new objects by copying those prototypes.

Example of a program: Create a new resume from a CV prototype

Code features: Resume class Resume provides a clone () method that is not actually clone, but adds a reference to an existing object.

The copy and Deepcopy methods in the Copy module provided by Python have implemented prototype patterns, but because of the shallow level of the examples, they do not see the difference.

    

prototype Mode

Seven, template method mode

Pattern Features: Define an algorithmic skeleton in an operation, delaying some steps into subclasses.

Program Example: Use the same test paper (parent class), different students submit their own papers (subclass method implementation)

Code Features: None

Template Method Mode

Eight, the appearance mode

Pattern Feature: Provides a consistent interface for a set of calls.

Program instance: The interface combines several calls into two groups, and the user calls one of the groups through the interface.

Code Features: None

appearance mode

Nine, builder model

Pattern feature: Separates the construction of a complex object (Director) from its representation (Builder) so that the same build process can create different representations (ConcreteBuilder).

Program Example: "Draw" a villain with a perfect limb (head leg)

Code Features: None

Builder Mode

X. Observer pattern

Pattern Features: Defines a one-to-many relationship that allows multiple observers to listen to a Subject object at the same time, notifying all observers when the subject's state changes.

Example of a program: There are two kinds of employees in the company who are lazy when the boss is absent: Watch the NBA and watch the stock market, and let the boss's secretary when the boss appears to inform them to continue to do the work at hand.

Program Features: None

Observer Pattern

XI. Abstract Factory Model

Pattern feature: Provides an interface that creates a series of related or interdependent objects without having to specify their classes.

Program instance: provides support for different database accesses.

Iuser and idepartment are two different kinds of abstract products that have two different implementations of access and SQL Server, ifactory are abstract factories that produce iuser and idepartment, The corresponding specific objects (Caccessuser and caccessdepartment, or Csqluser and csqldepartment) are produced according to the specific implementation (Accessfactory and Sqlfactory).

Code Features: None

Abstract Factory mode

12. State mode

Pattern feature: When an object's internal state changes to allow its behavior to change, the object looks like it has changed its class.

Program Example: Describe a programmer's working state, change when the state needs to change, different state of the method to achieve different

Code Features: None

State mode

13. Adapter Mode

Pattern feature: Transforms the interface of a class into another interface that the customer wants.

Program instance: A method by which a user uses a class through an adapter.

Code Features: None

Adapter Mode

14. Memo Mode

Pattern Features: captures the internal state of an object without compromising encapsulation, and saves the state outside of the object, which can later be restored to that state.

Program instance: Encapsulates the state of a originator object into a memo object saved in caretaker

Code Features: None

Memo Mode

XV, combination mode

Pattern feature: Combine objects into a tree structure to represent a "partial-whole" hierarchy

Program Examples: Organizational structure of company personnel

Code Features: None

Combination Mode

16. Iterator mode

Pattern Features: Provides methods to sequentially access elements of an aggregation object without exposing the object's internal representation

Description: This pattern is not written in code, because the Python list and for ... in list can be used to iterate over different types of object aggregation.

17. Single Case mode

Pattern Feature: guarantees that the class has only one instance and provides a global access point to access it.

Note: In order to achieve a single model cost a lot of work, and later found a blog post on this has a very detailed introduction, and the way of implementation is also very rich, through the code to learn more about the use of Python. The following code is from Ghostfromheaven's column, Address: http://blog.csdn.net/ghostfromheaven/article/details/7671853. But as its author in the Python single-mode Ultimate Edition says:

What I'm asking is, does Python really need a singleton mode? I'm referring to the singleton pattern in other programming languages.

The answer is: no need!

Because Python has a module, the most pythonic example of a single case.

module in one application only one, it is a singleton, the properties and methods you need, directly exposed in the module into the module's global variables and methods can!

Singleton Mode (four methods)

18. Bridging mode

Pattern Features: Separate the abstract part from its implementation, so that they can all change independently.

Program Example: Two brands of mobile phones, they can run games and contacts two software, rather than for each brand of mobile phones are independent of writing different software.

Code features: Although a new class of object is used, it is not required here, it is a demonstration of the recommendation to "use the new class as much as possible" after Python2.2.

Bridging Mode

19. Command mode

Pattern feature: Encapsulates a request into an object so that different requests can be parameterized by the client, queued to the request, or logged in the request log, and supports undoable operations.

Program Example: The grill has two kinds of food, mutton kebabs and chicken wings. The customer orders to the waiter, the waiter will order a good order to tell the chef, cooked by the chef.

Code Features: Note that you should not delete comments when traversing the list, otherwise a bug will occur. The Bug sample program is attached to the back, which I think is because remove disrupts the order of the for Iteration query list.

Command mode

Remove in for is the presentation code that causes the bug:

Bug

20. Responsibility Chain Mode

Pattern Features: Enables multiple objects to have the opportunity to process requests, thus avoiding the coupling between sender and receiver. Links the object to a chain and passes the request along the chain until it is processed.

Program example: Leave and raise the request to the superior, if the superior is not authorized to decide, then submitted to the superior.

Code Features: None

Responsibility Chain Model

21. Intermediary mode

Pattern Feature: Use an object to encapsulate a series of object interactions, and the mediator makes the objects not need to be referenced to each other, which makes the coupling loose and can change the interaction between them independently.

Example of a program: two objects communicate with each other through intermediaries

Code Features: None

Broker Mode

22. Enjoy meta mode

Pattern Features: The use of shared technology to effectively support a large number of fine-grained objects.

Program instance: A site factory that returns the appropriate category of sites based on the category requested by the user. If the site of this category is already on the server, then return this site and add the unique data of different users, if not, then generate one.

Code features: To show the number of user requests per site, a dictionary of references has been created for them.

The reason for not using the Sys.getrefcount () method in the Python sys module to count reference counts is that some objects may be implicitly referenced elsewhere, thus increasing the reference count.

enjoy meta mode

23. Interpreter Mode

Pattern features: Given a language, define a representation of its grammar and define an interpreter that uses that representation to interpret sentences in the language.

Program Examples: (just the simplest demonstration of the pattern features)

Code Features: None

Interpreter Mode

24. Visitor Mode

Pattern Feature: Represents an operation that acts on elements in an object's structure. It allows you to define new actions that act on these elements without changing the class of each element.

Examples of programs: For Men and women (the elements that accept visitors, objectstructure are used for the poor lifting of these elements), different encounters (specific visitors) trigger different behaviors of the two objects.

Code Features: None

Visitor Mode

Resources:

Http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html

Python, "Big talk design mode", code implementation

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.