#-*-Coding:utf-8-*-
__author__ = ' Administrator '
#python高级编程: A useful design pattern
#设计械是可复用的, some of the most popular books in a program that provide language-related solutions to the problems of software design awareness:
"""
Gamma, Heim, Johson and Vlissides a.k.a "Foursome (GOF)" written elements of reusable object-oriented software (Chinese:< design mode: Reusable Object-oriented Software Foundation >)
It is considered an important piece of work in this field
Python offers 3 design patterns:
"""
#创建型模式: Used to generate object patterns with specific behavior
"" It provides an instantiation mechanism, which can be a special object factory or even a class factory, which is a very important pattern in a compiled language such as x, because it is more difficult to generate types as required at run time
, but in Python, these are built-in, such as type, that can be defined by code to define a new type, as follows: ""
Mytext=type (' Mytyper ', (object,), {' A ': 1})
Ob=mytext ()
Print type (OB)
Print OB.A
Print Isinstance (ob,object)
"""
Classes and types are built-in factories that are the basis for implementing factory design Patterns
In addition to the factory, the only interesting creation pattern for Gof in Python is the singleton mode (singleton)
"""
#单例模式: Used to restrict a class to be instantiated only as an object
"""
The singleton pattern ensures that a given class always has only one instance in the application. For example, you can use a resource when you want to restrict access to one of the resources in a process and have only one intrinsic context.
For example: A Database Connector class is a singleton that processes synchronization and its data in memory, assuming that no other instance interacts with the database at the same time.
This pattern can greatly simplify the processing of concurrency in the application, and utilities that provide functionality throughout the application are often declared as Singleton, which is explained by the following example
Use the __new__ method, as follows:
"""
Class A (object):
Def __new__ (CLS, *args, **kwargs):
If not hasattr (CLS, ' _instance '):
Orig=super (A,CLS)
cls._instance=orig.__new__ (Cls,*args,**kwargs)
Return cls._instance
Class B (A):
A=1
One=b ()
Two=b ()
Two.a=3
Print One.a
#不过这种模式子类化方面也存在一些问题-All instantiations are instances of B, regardless of the result of the method parsing order (__mro__), as follows:
Class C (B):
b=2
Tree=c ()
#print tree.battributeerror: ' B ' object has no attribute ' B '
"""
To avoid this limitation, Alex Martelli provides a shared-state-based alternative implementation, namely Borg
The idea is that what is really important in a singleton pattern is how many instances of the class exist, and that they will share the same state of fact at all times, so
Alex Martelli introduced a class that uses all instances to share the same __dict__, as follows:
"""
Class Borg (object):
_state={}
Def __new__ (CLS, *args, **kwargs):
Ob=super (BORG,CLS). __new__ (Cls,*args,**kwargs)
Ob.__dict__=cls._state
Return OB
Class B1 (Borg):
A=1
A=B1 ()
B=B1 ()
B.a=3
Print A.A
Class B2 (B1):
b=2
TREE=B2 ()
Print tree.b
Print Tree.a
tree.a=2
Print A.A
"""
This solves the problem of subclasses, but still depends on how the subclass code works, and if __getattr__ is overloaded, then this pattern can be corrupted.
Even so, a singleton should not have multiple levels of inheritance, and a class marked as a singleton is already a special class.
That is, this pattern is seen by many developers as an important way to deal with application uniqueness issues, and if a singleton is required, since the Python schema is also a singleton,
So why not use a module with a function instead?
A singleton factory is an implicit method of uniqueness in an you application, or it can be used without it, except in a Java-style framework, where modules are used instead of classes
"""
#结构型模式 code structure patterns that are useful for specific usage scenarios
"""
They determine how the code is organized and provide a way for developers to interact with each part of the application.
In the Python world, the most famous implementation is the Zope component Architecture (Zope component Architecture, abbreviated to ZCA, see: It implements most of the patterns and provides a rich toolset for working with these patterns, Zca not only the Zope framework, but also other frameworks such as twisted, as well as an implementation of interfaces and adapters.
So even a small piece of work should consider using it instead of rewriting it from scratch.
There are a lot of structural patterns that inherit from the original gof11.
An adorner function is allowed, but is not extended to a class in a future release at run time
as follows: http://www.python.org/dev/peps/pep-3129
Other popular patterns are:
"""
#适配器: Used to close a class or an object A, which can work in the context of a class or object B
#当一些代码被用来处理一个指定的类, it is good to give it objects from another class, which provides the methods and features used by the code, which forms the basis of the duck-typing idea in Python.
#如果它走起来像鸭子, it sounds like a duck, so it's a duck.
#当然, this assumes that the code does not call instanceof to verify that the instance is a specific class
#我说它是一个鸭子, there's no need to check its DNA.
#行为型模式 a pattern that helps to structure a process
"""
The adapter is based on this idea and defines a encapsulation mechanism in which a class or object is encapsulated in order to make it work in a context that is not provided for it, Stringio is a typical example
It adapts the STR type so that it can be used just like the file type:
"""
From Stringio import Stringio
My_file=stringio (U ' some content ')
Print My_file.read ()
My_file.seek (0)
Print My_file.read (1)
"""
For example, the Dublincoreinfos class knows how to display Dublin core information for a specified document (see http://dublincore.org), which reads several fields
such as the author name or title and print, in order to be able to display Dublin Core for a file, it must be the same as Stringio, the above picture gives the pattern class-UML diagram, this class provides an instance, and provides metadata access to it, as follows:
"""
From Os.path import Split,splitext
Class Dublincoreinfos (object):
def __init__ (self,filename):
Self._filename=filename
def title (self):
Return Splitext (Split (Self._filename) [-1]) [0]
def creator (self):
Return ' Unknow ' #真实获取
def languages (self):
Return (' en ',)
Class Dublincoreinfosinfo (object):
Def summary (SELF,DC_OB):
print ' title:%s '%dc_ob.title ()
print ' creator:%s '%dc_ob.creator ()
print ' Languages:%s ', ', '. Join (Dc_ob.languages ())
Adatep=dublincoreinfos (' Example.txt ')
Info=dublincoreinfosinfo ()
Info.summary (Adatep)
"""
In addition to allowing replacements, the adapter pattern does not change the developer's work, adapting an object to work in a specific context, and imagining what class of object is irrelevant
What is important is that this class Dublincoreinfosinfo () is expected to have a feature that is fixed or completed by an adapter, so that the code can somehow tell it to be compatible with the object that implements the specific behavior, and that it is represented by an interface (interfaces)
"""
#1: interface
"""
is a definition of the API that describes the list of methods and attributes that a class must implement for the desired behavior, and this description does not implement any code, only defines the explicit contract (contract) used by the class of the interface that you want to implement, and any class can implement one or more objects in the way that it wants.
While in Python, the duck typing is preferred over the connection definition, but sometimes it may be better to use an interface
The advantage of this is that the class is low-coupling, which is considered a good practice
Many developers require the interface to be added as a core feature of Python, and the current people who want to use the interface are now forced to use the Zope interface or Pyprotocols
Previously, Guido refused to add interfaces to Python because they were not suitable for Python's dynamic duck-typing features, but the interface system proved their value in some cases, so python3000 would introduce a known
Option type annotations (optional type symbol), which can be used as a syntax for third-party interface libraries
"""
"""
Recently Python 3000 also added abstract base class (ABC) support, the following is an excerpt from THE PEP
<ABC is simply a Python class that is added to object inheritance, which is used to communicate some of the object's functionality to an external checker >
The adapter is perfect for keeping the class and execution context coupled, but if the adaptation is used as a programming idea, rather than as a must-have in a particular procedure
object to do a quick fix, then the interface should be used.
"""
Python advanced Programming: useful Design Patterns 1