Alibabacloud.com offers a wide variety of articles about python design patterns book, easily find your python design patterns book information here online.
disadvantage of the singleton mode?While the singleton mode works fine but there are still some problems because the singleton has global access, the following issues may occur:
Multiple references to the same object may be created 。 Because a singleton creates only one object, a reference is created on an object in this case.
So far, we have introduced the singleton model of the relevant content, follow-up may write about other
1. due to the different characteristics of the language, the design mode and implementation of the difficulty will be different2. Some patterns have been built into the language, such as the iterator pattern. 3. The singleton mode can be directly implemented with module-level variables .4. Normal Factory mode can be implemented directly by passing in "class name" as parameterSingleton Mode Example:12_eg.pyC
):If OBJS in Cls._obj:Cls._obj.remove (OBJS)@classmethoddef 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._objWritevent.reg (log)Class Anot (object):def __call__ (self, E):print ' Yean%s told me! ' %eWritevent.reg (Anot)WRITEVENT.NOT1 (' A given file ')#对这个实现, the follow
It seems that the following is the most elegant implementation.Other, either node redundancy, or initialize ugly ...#!/usr/bin/env python#-*-coding:utf-8-*-classNode:def __init__(self, initdata): Self.__data=InitData self.__next=NonedefGetData (self):returnSelf.__data defGetNext (self):returnSelf.__next defSetData (Self, newdata): Self.__data=NewDatadefSetnext (Self, newnext): Self.__next=Newnextclasssincyclinkedlist:def __init__(self): Self.head=No
fraiche sauce') defadd_topping (self):Print('adding the topping (Mozzaralla, bacon, ham, mushrooms, red onion, oregano) to you creamy bacon') self.pizza.topping.append ([t forTinch(Pizzatopping.mozzaralla, Pizzatopping.bacon, Pi Zzatopping.ham, Pizzatopping.mushrooms, Pizzatopping.red_onion, Pizzatopping.oregano)]) Time.sleep (Step_delay)Print('Done with the topping (mozzarella, bacon, ham, mushrooms, red onion, oregano)') defBake (self): self.progress=pizzaprogress.bakingPrint('B
. Intermediary mode (mediator pattern): Use the mediator mode to centralize the complex communication and control between related objects.6. Memo Mode (Memento pattern): When you need to return an object to its previous state (for example, your user requests "undo"), you use Memo mode.7. Observer pattern (Observer pattern): Defines a one-to-many dependency between objects, so that when an object changes state, objects that depend on it are notified and updated automatically.8. State pattern: All
The singleton pattern appears as a substitute for " global Variables " . So it has the characteristics of global variables: globally visible, throughout the lifetime of the application, to ensure that in the program run, a class only one instance, so the constructor in the class is usually not expected to be calledPython:Class single (object): Instance = None#def __init__ (self):p ass#def getinstance (self): if single.instance = = None: Single.instance = single () return single.instance#def prin
principle:
strive for loose coupling between interactive objects.
The book mainly cites an example of the application of meteorological monitoring. The application of the observer model can be a good solution to this problem. Let's look at the Designed class diagram first.
The final code implemented in Python is as follows:
"' The second design pattern:observ
): Start_response (status= ' OK ', headers=[(' Content-type ', ' text/html ')]) url=environ[' Path_info '] #这is the URL that the user accesses #这里我们访问http://127.0.0.1:8000 if Url.endswith (' index '): #根据网页以什么什么结尾则决定调用的函数 return index () elif u Rl.endswith (' News '): Return News () Else:return ' 404 "" means that when we visit Http://127.0.0.1:8000/index, the index function is returned The results of the implementation, the other equivalent here to engage a website "if __name__ = = ' __main__ '
The simple factory pattern is a class-created pattern that is suitable for instantiating a large number of classes with common interfaces, and it can be deferred until run to dynamically determine which class to create, rather than having to know which class to instantiate at compile time.Python:#!/usr/bin/env python#-*-coding:utf-8-*-class Circle (object):d EF Draw (self):p rint ' Draw Circle ' class Rectangle ( Object):d EF Draw (self):p rint ' Draw
The observer pattern in the design pattern is defined as follows (Wikipedia):
The viewer model (sometimes called the fabric/subscribe mode) is one of the software design patterns. In this pattern, a target object manages all the objects that are dependent on it, and notifies you of its own state change. This is usually done through the means of calling the viewe
The singleton pattern appears as a substitute for " global Variables " . So it has the characteristics of global variables: globally visible, throughout the lifetime of the application, to ensure that in program execution, a class exists only one instance, so the constructor in the class is usually not expected to be calledPython:Class single (object): Instance = None#def __init__ (self):p ass#def getinstance (self): if single.instance = = None: Single.instance = single () return single.instance
experience reach a certain level, and it also means to summarize a lot of good design experience, however, it may not be the case that "no teacher can do anything", or you can say that, on the basis of level and experience, it is time for the system to learn the "mode, it is helpful to learn the experts' summary and verify your own shortcomings.
This series of design p
expanded, without affecting the parts that don't need to change. In fact, if you go back and read the book of design patterns, you'll find that encapsulation changes are almost the spirit behind each design pattern. All patterns provide a way for a part of the system to cha
Design Mode----Design Mode Summary (end)
From the study of design patterns to the study of visitor patterns, the learning process of my design patterns has ended. This process laste
written two books of great influence, namely (a pattern language and timeless architecture). For the first time, the design pattern of architecture is described in the book. Through the precise definition of a series of architectural features, Alexander tries to extract the essence of architectural design that brings happiness to residents.The interaction
Design patterns are a set of reusable, most known, categorized purposes, code design experience Summary. Design patterns are used in order to reuse code, make code easier for others to understand, and ensure code reliability.The origins of
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.