⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sect02.htm

📁 Pythn design pattern
💻 HTM
📖 第 1 页 / 共 3 页
字号:
<font color=#0000ff>print</font> x
y = Singleton('eggs')
<font color=#0000ff>print</font> y
z = Singleton('spam')
<font color=#0000ff>print</font> z
<font color=#0000ff>print</font> x
<font color=#0000ff>print</font> y
<font color=#0000ff>print</font> &#180;x&#180;
<font color=#0000ff>print</font> &#180;y&#180;
<font color=#0000ff>print</font> &#180;z&#180;
output = '''
sausage
eggs
spam
spam
spam
&lt;__main__.Singleton instance at 0079EF2C&gt;
&lt;__main__.Singleton instance at 0079E10C&gt;
&lt;__main__.Singleton instance at 00798F9C&gt;
'''
#:~</PRE></FONT></BLOCKQUOTE><DIV ALIGN="LEFT"><P><FONT FACE="Georgia">This has an identical effect as
<B>SingletonPattern.py</B> does, but it&#146;s more elegant. In the former
case, you must wire in <I>Singleton</I> behavior to each of your classes, but
<I>Borg</I> is designed to be easily reused through inheritance.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_64">Add Comment</A></FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Two other interesting ways to define
singleton</FONT><A NAME="fnB10" HREF="#fn10">[10]</A><FONT FACE="Georgia">
include wrapping a class and using metaclasses. The first approach could be
thought of as a <I>class decorator</I> (decorators will be defined later in the
book), because it takes the class of interest and adds functionality to it by
wrapping it in another class:</FONT><BR></P></DIV>

<BLOCKQUOTE><FONT SIZE = "+1"><PRE>#: c01:SingletonDecorator.py
<font color=#0000ff>class</font> SingletonDecorator:
  <font color=#0000ff>def</font> __init__(self,klass):
    self.klass = klass
    self.instance = None
  <font color=#0000ff>def</font> __call__(self,*args,**kwds):
    <font color=#0000ff>if</font> self.instance == None:
      self.instance = self.klass(*args,**kwds)
    <font color=#0000ff>return</font> self.instance

<font color=#0000ff>class</font> foo: <font color=#0000ff>pass</font>
foo = SingletonDecorator(foo)

x=foo()
y=foo()
z=foo()
x.val = 'sausage'
y.val = 'eggs'
z.val = 'spam'
<font color=#0000ff>print</font> x.val
<font color=#0000ff>print</font> y.val
<font color=#0000ff>print</font> z.val
<font color=#0000ff>print</font> x <font color=#0000ff>is</font> y <font color=#0000ff>is</font> z
#:~</PRE></FONT></BLOCKQUOTE><DIV ALIGN="LEFT"><P><FONT FACE="Georgia">[[ Description ]]
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A1_64">Add Comment</A></FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The second approach uses metaclasses, a
topic I do not yet understand but which looks very interesting and powerful
indeed (note that Python 2.2 has improved/simplified the metaclass syntax, and
so this example may change):</FONT><BR></P></DIV>

<BLOCKQUOTE><FONT SIZE = "+1"><PRE>#: c01:SingletonMetaClass.py
<font color=#0000ff>class</font> SingletonMetaClass(type):
  <font color=#0000ff>def</font> __init__(cls,name,bases,dict):
    super(SingletonMetaClass,cls)\
      .__init__(name,bases,dict)
    original_new = cls.__new__
    <font color=#0000ff>def</font> my_new(cls,*args,**kwds):
      <font color=#0000ff>if</font> cls.instance == None:
        cls.instance = \
          original_new(cls,*args,**kwds)
      <font color=#0000ff>return</font> cls.instance
    cls.instance = None
    cls.__new__ = staticmethod(my_new)

<font color=#0000ff>class</font> bar(object):
  __metaclass__ = SingletonMetaClass
  <font color=#0000ff>def</font> __init__(self,val):
    self.val = val
  <font color=#0000ff>def</font> __str__(self):
    <font color=#0000ff>return</font> &#180;self&#180; + self.val

x=bar('sausage')
y=bar('eggs')
z=bar('spam')
<font color=#0000ff>print</font> x
<font color=#0000ff>print</font> y
<font color=#0000ff>print</font> z
<font color=#0000ff>print</font> x <font color=#0000ff>is</font> y <font color=#0000ff>is</font> z
#:~</PRE></FONT></BLOCKQUOTE><DIV ALIGN="LEFT"><P><FONT FACE="Georgia">[[ Long, detailed, informative
description of what metaclasses are and how they work, magically inserted here
]]
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A1_65">Add Comment</A></FONT><BR></P></DIV>
<A NAME="Heading18"></A><FONT FACE = "Verdana, Tahoma, Arial, Helvetica, Sans"><H4 ALIGN="LEFT">
Exercise:</H4></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Modify <B>BorgSingleton.py</B> so that it
uses a class <B>__new__( )</B> method.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_65">Add Comment</A></FONT><A NAME="_Toc476705895"></A><A NAME="_Toc534420068"></A><BR></P></DIV>
<A NAME="Heading19"></A><FONT FACE = "Verdana, Tahoma, Arial, Helvetica, Sans"><H2 ALIGN="LEFT">
Classifying patterns</H2></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The <I>Design Patterns</I> book discusses
23 different patterns, classified under three purposes (all of which revolve
around the particular aspect that can vary). The three purposes are:
<A NAME="Index12"></A><A NAME="Index13"></A><A NAME="Index14"></A><A NAME="Index15"></A><A NAME="Index16"></A><A NAME="Index17"></A><A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_66">Add Comment</A></FONT><BR></P></DIV>
<OL>
<LI><FONT FACE="Verdana"><B>	</B></FONT><FONT FACE="Georgia"><B>Creational</B>:
how an object can be created. This often involves isolating the details of
object creation so your code isn&#146;t dependent on what types of objects
there are and thus doesn&#146;t have to be changed when you add a new type of
object. The aforementioned <I>Singleton</I> is classified as a creational
pattern, and later in this book you&#146;ll see examples of <I>Factory
Method</I> and <I>Prototype</I>.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_67">Add Comment</A></FONT><LI><FONT FACE="Verdana"><B>	</B></FONT><FONT FACE="Georgia"><B>Structural</B>:
designing objects to satisfy particular project constraints. These work with the
way objects are connected with other objects to ensure that changes in the
system don&#146;t require changes to those connections.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_68">Add Comment</A></FONT><LI><FONT FACE="Verdana"><B>	</B></FONT><FONT FACE="Georgia"><B>Behavioral</B>:
objects that handle particular types of actions within a program. These
encapsulate processes that you want to perform, such as interpreting a language,
fulfilling a request, moving through a sequence (as in an iterator), or
implementing an algorithm. This book contains examples of the <I>Observer</I>
and the <I>Visitor</I> patterns.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_69">Add Comment</A></FONT></OL><DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The
<I>Design Patterns</I> book has a section on each of its 23 patterns along with
one or more examples for each, typically in C++ but sometimes in Smalltalk.
(You&#146;ll find that this doesn&#146;t matter too much since you can easily
translate the concepts from either language into Python.) This book will not
repeat all the patterns shown in <I>Design Patterns</I> since that book stands
on its own and should be studied separately. Instead, this book will give some
examples that should provide you with a decent feel for what patterns are about
and why they are so important.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_70">Add Comment</A></FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">After years of looking at these things,
it began to occur to me that the patterns themselves use basic principles of
organization, other than (and more fundamental than) those described in
<I>Design Patterns</I>. These principles are based on the structure of the
implementations, which is where I have seen great similarities between patterns
(more than those expressed in <I>Design Patterns</I>). Although we generally try
to avoid implementation in favor of interface,<I> </I>I have found that
it&#146;s often easier to think about, and especially to learn about, the
patterns in terms of these structural principles. This book will attempt to
present the patterns based on their structure instead of the categories
presented in <I>Design Patterns</I>.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_71">Add Comment</A></FONT><A NAME="_Toc534420069"></A><BR></P></DIV>
<A NAME="Heading20"></A><FONT FACE = "Verdana, Tahoma, Arial, Helvetica, Sans"><H2 ALIGN="LEFT">
The development challenge</H2></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Issues of development, the UML process,
Extreme Programming.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_72">Add Comment</A></FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Is evaluation valuable? The Capability
Immaturity Model:</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Wiki Page:
<A HREF="http://c2.com/cgi-bin/wiki?CapabilityImMaturityModel">http://c2.com/cgi-bin/wiki?CapabilityImMaturityModel</A></FONT><BR><FONT FACE="Georgia">Article:
<A HREF="http://www.embedded.com/98/9807br.htm">http://www.embedded.com/98/9807br.htm</A></FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia" COLOR="Blue"><U>
</U></FONT><FONT FACE="Georgia"><A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_73">Add Comment</A></FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia"><I>Pair programming</I>
research:</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia"><A HREF="http://collaboration.csc.ncsu.edu/laurie/">http://collaboration.csc.ncsu.edu/laurie/</A></FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_74">Add Comment</A></FONT><A NAME="_Toc534420070"></A><BR></P></DIV>
<A NAME="Heading21"></A><FONT FACE = "Verdana, Tahoma, Arial, Helvetica, Sans"><H2 ALIGN="LEFT">
Exercises</H2></FONT>
<OL>
<LI><FONT FACE="Verdana">	</FONT><FONT FACE="Georgia"><B>SingletonPattern.py</B>
always creates an object, even if it&#146;s never used. Modify this program to
use <I>lazy initialization</I>, so the singleton object is only created the
first time that it is needed.<B>
</B><A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_75">Add Comment</A></FONT><LI><FONT FACE="Verdana">	</FONT><FONT FACE="Georgia">Using
<B>SingletonPattern.py</B> as a starting point, create a class that manages a
fixed number of its own objects. Assume the objects are database connections and
you only have a license to use a fixed quantity of these at any one time.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_76">Add Comment</A></FONT></OL>
<HR><DIV ALIGN="LEFT"><P><A NAME="fn3" HREF="#fnB3">[3]</A><FONT FACE="Georgia"> From
Mark Johnson.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><A NAME="fn4" HREF="#fnB4">[4]</A><FONT FACE="Georgia">
</FONT><FONT FACE="Georgia">But be warned: the examples are in
C++.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><A NAME="fn5" HREF="#fnB5">[5]</A><FONT FACE="Georgia"> This
list includes suggestions by Kevlin Henney, David Scott, and
others.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><A NAME="fn6" HREF="#fnB6">[6]</A><FONT FACE="Georgia"> A free
email publication. See www.BruceEckel.com to subscribe.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><A NAME="fn7" HREF="#fnB7">[7]</A><FONT FACE="Georgia"> This
idea is generally attributed to Antoine de St. Exupery from <I>The Little
Prince</I>: "La perfection est atteinte non quand il ne reste rien &agrave;
ajouter, mais quand il ne reste rien &agrave; enlever," or: "perfection is
reached not when there's nothing left to add, but when there's nothing left to
remove".  </FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><A NAME="fn8" HREF="#fnB8">[8]</A><FONT FACE="Georgia"> From
an email from Kevlin Henney.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><A NAME="fn9" HREF="#fnB9">[9]</A><FONT FACE="Georgia"> From
the television show <I>Star Trek: The Next Generation</I>. The Borg are a
hive-mind collective: &#147;we are all one.&#148;</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><A NAME="fn10" HREF="#fnB10">[10]</A><FONT FACE="Georgia">
Suggested by Chih-Chung Chang.</FONT><BR></P></DIV>

<DIV ALIGN="CENTER">
    <FONT FACE="Verdana, Tahoma, Arial, Helvetica, Sans" size = "-1">
     [ <a href="Sect01.htm">Previous Chapter</a> ] 
    
    [ <a href="javascript:window.location.href = 'Index.htm';">Table of Contents</a> ] 
  
        [ <a href="DocIdx.htm">Index</a> ]
        
     [ <a href="Sect03.htm">Next Chapter</a> ] 
    </FONT>
    <BR>
 Last Update:12/31/2001</P></DIV>

</BODY>

</HTML>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -