Python advanced Programming: useful Design Patterns 2

Source: Internet
Author: User

#-*-Coding:utf-8-*-

__author__ = ' Administrator '

#python高级编程: A useful design pattern

#代理

"""

Proxies provide a non-direct access mechanism to a costly or remote resource

Between the customer and the idea,. It is used to optimize access to high-cost topics, such as the memoize adorner described in the previous chapter can be considered a proxy

, it can also be used to provide smart access to a topic, for example, large video files can be enclosed in proxies to avoid loading files into memory when users simply consult their titles

The URLLIB2 gives an example, as follows:

"""

From URLLIB2 Import *

Class Url (object):

def __init__ (Self,url):

Self._url=urlopen (URL)

def Headrs (self):

Return Dict (Self._url.headers.items ())

def get (self):

Return Self._url.read ()

Python_org=url (' http://python.org ')

Print Python_org.headrs ()

"""

You can also use to get the page body to update the local copy by looking at the header last-modifed to determine if the page has changed

As follows:

"""

Python1=url (' Http://ubuntu.mirrors.proxad.net/hardy/ubuntu-8.04-desktop-i386.iso ')

Print python1.headrs[' last-modified '] #可能会报错

"""

Another usage scenario for proxies is data uniqueness;

For example, a Web site that displays the same document in more than one place, the document attaches extra fields for each location, such as access count and several license settings, which the agent can use to handle location-related events, and point to the original document instead of copying it, so that a specified document can have many proxies, If the content of it changes.

All locations will benefit from not having to deal with version synchronization;

Using a proxy as a local handle to something that might exist somewhere else, you can:

Make the process faster

Avoid external resource access

Reduce memory load

Ensuring uniqueness of data

"""

#外观: Provides simpler access to subsystems

"""

It is just a shortcut to a feature that uses the application, and does not require the underlying complexity of the corresponding subsystem, such as: it can be done by providing a higher function at the package level.

The appearance model is used on the basis of the existing system, where the perception of the package is integrated into a high-level function, which is generally not required to provide such a pattern

A simple function in the __init__.py module is possible.

The use of the appearance simplification package is usually added after several iterations with feedback

"""

#行为型模式 a pattern that helps to structure a process

# #观察者 (Observer)

"""

Used to inform a range of object state changes. You can use the Watch mode to add attributes in an application in an pluggable manner, and to decouple the existing code base from the new functionality.

The event framework is a typical observer implementation where all observers of an event are notified of the object that triggered the event whenever an event occurs.

Events are moments of events that occur in a graphical interface application, event-driven programming (see: Http://en.wikipedia.org/wiki/eventdriven_programming)

Often used to implement code-to-user links, for example, a function can be linked to a MouseMove event so that whenever the mouse moves over the window, the function is called,

In such cases, coupling the code from Window management events greatly simplifies the work: functions are written separately and registered as event observers:

This approach from the MFC framework of Microsoft Corporation (http://en.wikipedia.org/wiki/microsoft_foundation_class_library)

Is present in all GUI development tools (such as Delphi).

But the code can also generate events, for example, in a document stored in a database application, the code might provide

Documentcreated,docmentmodified and Documentdeleted3 Events

A new document-specific feature can register itself as an observer, be notified when a file is created, modified or deleted, and work accordingly, so that it can be indexed in a document, which, of course, is responsible for creating, modifying, or deleting a document's code-triggering event

However, this is much easier than adding a hook program that is indexed everywhere in the application code base.

In Python you can use the event to implement the above mentioned, as follows:

"""

Class Event (object):

_obj=[]

def __init__ (self,obj1):

Self.obj1=obj1

@classmethod

DEF reg (CLS,OBJS):

If Objs not in Cls._obj:

Cls._obj.append (OBJS)

@classmethod

def REG1 (CLS,OBJS):

If OBJS in Cls._obj:

Cls._obj.remove (OBJS)

@classmethod

def not1 (cls,sub):

Event=cls (sub)

For O in Cls._obj:

O (Event)

#思路是观察者使用event类方法注册自己, and is obtained by carrying the event that triggers these events, as follows:

Class Writevent (object):

def __repr__ (self):

Return ' writevent (self) '

Def log (event):

print '%s:was writees '%event._obj

Writevent.reg (log)

Class Anot (object):

def __call__ (self, E):

print ' Yean%s told me! ' %e

Writevent.reg (Anot)

WRITEVENT.NOT1 (' A given file ')

#对这个实现, the following improvements can be made:

"""

Allow developers to modify the order

Keep Event objects more information than topics

If you want to use an existing tool, you can use Pydispatch, which provides a good scheduling mechanism for multi-consumer and multi-producer

(http://www.sqlobject.org/module-sqlobject.pydispatch.html)

"""

Python advanced Programming: useful Design Patterns 2

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.