Commits

Anonymous committed fd2bab7

update from Bruce

  • Participants
  • Parent commits b489dad

Comments (0)

Files changed (24)

File src/AppFrameworks.rst

+
+*******************************************************************************
+Building Application Frameworks
+*******************************************************************************
+
+An application framework allows you to inherit from a class or set of classes
+and create a new application, reusing most of the code in the existing classes
+and overriding one or more methods in order to customize the application to your
+needs. A fundamental concept in the application framework is the *Template
+Method* which is typically hidden beneath the covers and drives the application
+by calling the various methods in the base class (some of which you have
+overridden in order to create the application).
+
+For example, whenever you create an applet you're using an application
+framework: you inherit from **JApplet** and then override **init( )**. The
+applet mechanism (which is a *Template Method*) does the rest by drawing the
+screen, handling the event loop, resizing, etc.
+
+Template Method
+=======================================================================
+
+An important characteristic of the *Template Method* is that it is defined in
+the base class and cannot be changed. It's sometimes a **private** method but
+it's virtually always **final**. It calls other base-class methods (the ones you
+override) in order to do its job, but it is usually called only as part of an
+initialization process (and thus the client programmer isn't necessarily able to
+call it directly)::
+
+    # AppFrameworks/TemplateMethod.py
+    # Simple demonstration of Template Method.
+
+    class ApplicationFramework:
+        def __init__(self):
+            self.__templateMethod()
+        def __templateMethod(self):
+            for i in range(5):
+                self.customize1()
+                self.customize2()
+
+    # Create an "application":
+    class MyApp(ApplicationFramework):
+        def customize1(self):
+            print("Nudge, nudge, wink, wink! ",)
+        def customize2(self):
+            print("Say no more, Say no more!")
+
+    MyApp()
+
+
+
+The base-class constructor is responsible for performing the necessary
+initialization and then starting the "engine" (the template method) that runs
+the application (in a GUI application, this "engine" would be the main event
+loop). The client programmer simply provides definitions for **customize1( )**
+and **customize2( )** and the "application" is ready to run.
+
+We'll see *Template Method* numerous other times throughout the book.
+
+Exercises
+=======================================================================
+
+#.  Create a framework that takes a list of file names on the command line. It
+    opens each file except the last for reading, and the last for writing. The
+    framework will process each input file using an undetermined policy and
+    write the output to the last file. Inherit to customize this framework to
+    create two separate applications:
+
+        #. Converts all the letters in each file to uppercase.
+        #. Searches the files for words given in the first file.
+
+
+

File src/ChangeInterface.rst

+
+********************************************************************************
+Changing the Interface
+********************************************************************************
+
+Sometimes the problem that you're solving is as simple as "I don't have the
+interface that I want." Two of the patterns in *Design Patterns* solve this
+problem: *Adapter* takes one type and produces an interface to some other type.
+*Façade* creates an interface to a set of classes, simply to provide a more
+comfortable way to deal with a library or bundle of resources.
+
+Adapter
+=======================================================================
+
+When you've got *this*, and you need *that*, *Adapter* solves the problem. The
+only requirement is to produce a *that*, and there are a number of ways you can
+accomplish this adaptation::
+
+    # ChangeInterface/Adapter.py
+    # Variations on the Adapter pattern.
+
+    class WhatIHave:
+        def g(self): pass
+        def h(self): pass
+
+    class WhatIWant:
+        def f(self): pass
+
+    class ProxyAdapter(WhatIWant):
+        def __init__(self, whatIHave):
+            self.whatIHave = whatIHave
+
+        def f(self):
+            # Implement behavior using
+            # methods in WhatIHave:
+            self.whatIHave.g()
+            self.whatIHave.h()
+
+    class WhatIUse:
+        def op(self, whatIWant):
+            whatIWant.f()
+
+    # Approach 2: build adapter use into op():
+    class WhatIUse2(WhatIUse):
+        def op(self, whatIHave):
+            ProxyAdapter(whatIHave).f()
+
+    # Approach 3: build adapter into WhatIHave:
+    class WhatIHave2(WhatIHave, WhatIWant):
+        def f(self):
+            self.g()
+            self.h()
+
+    # Approach 4: use an inner class:
+    class WhatIHave3(WhatIHave):
+        class InnerAdapter(WhatIWant):
+            def __init__(self, outer):
+                self.outer = outer
+            def f(self):
+                self.outer.g()
+                self.outer.h()
+
+        def whatIWant(self):
+            return WhatIHave3.InnerAdapter(self)
+
+    whatIUse = WhatIUse()
+    whatIHave = WhatIHave()
+    adapt= ProxyAdapter(whatIHave)
+    whatIUse2 = WhatIUse2()
+    whatIHave2 = WhatIHave2()
+    whatIHave3 = WhatIHave3()
+    whatIUse.op(adapt)
+    # Approach 2:
+    whatIUse2.op(whatIHave)
+    # Approach 3:
+    whatIUse.op(whatIHave2)
+    # Approach 4:
+    whatIUse.op(whatIHave3.whatIWant())
+
+I'm taking liberties with the term "proxy" here, because in *Design Patterns*
+they assert that a proxy must have an identical interface with the object that
+it is a surrogate for. However, if you have the two words together: "proxy
+adapter," it is perhaps more reasonable.
+
+Façade
+=======================================================================
+
+A general principle that I apply when I'm casting about trying to mold
+requirements into a first-cut object is "If something is ugly, hide it inside an
+object." This is basically what *Façade* accomplishes. If you have a rather
+confusing collection of classes and interactions that the client programmer
+doesn't really need to see, then you can create an interface that is useful for
+the client programmer and that only presents what's necessary.
+
+Façade is often implemented as singleton abstract factory. Of course, you can
+easily get this effect by creating a class containing **static** factory
+methods::
+
+    # ChangeInterface/Facade.py
+    class A:
+        def __init__(self, x): pass
+    class B:
+        def __init__(self, x): pass
+    class C:
+        def __init__(self, x): pass
+
+    # Other classes that aren't exposed by the
+    # facade go here ...
+
+    class Facade:
+        def makeA(x): return A(x)
+        makeA = staticmethod(makeA)
+        def makeB(x): return B(x)
+        makeB = staticmethod(makeB)
+        def makeC(x): return C(x)
+        makeC = staticmethod(makeC)
+
+    # The client programmer gets the objects
+    # by calling the static methods:
+    a = Facade.makeA(1);
+    b = Facade.makeB(1);
+    c = Facade.makeC(1.0);
+
+[rewrite this section using research from Larman's book]
+
+Example for Facade (?): my "nicer" version of the XML library.
+
+Exercises
+=======================================================================
+
+#.  Create an adapter class that automatically loads a two-dimensional array of
+    objects into a dictionary as key-value pairs.
+
+
+

File src/Decorator.rst

+********************************************************************************
+Decorator: Dynamic Type Selection
+********************************************************************************
+
+..  note:: I think we can rewrite this chapter to use Python decorators as
+           implementation (thus the decorators chapter should precede this one).
+
+The use of layered objects to dynamically and transparently add responsibilities
+to individual objects is referred to as the *decorator* pattern.
+
+Used when subclassing creates too many (& inflexible) classes
+
+All decorators that wrap around the original object must have the same basic
+interface
+
+Dynamic proxy/surrogate?
+
+This accounts for the odd inheritance structure
+
+Tradeoff: coding is more complicated when using decorators
+
+Basic Decorator Structure
+=======================================================================
+
+.. image:: _images/decorator.*
+
+
+A Coffee Example
+=======================================================================
+
+Consider going down to the local coffee shop, *BeanMeUp*, for a coffee.  There
+are typically many different drinks on offer -- espressos, lattes, teas, iced
+coffees, hot chocolate to name a few, as well as a number of extras (which cost
+extra too) such as whipped cream or an extra shot of espresso. You can also make
+certain changes to your drink at no extra cost, such as asking for decaf coffee
+instead of regular coffee.
+
+Quite clearly if we are going to model all these drinks and combinations, there
+will be sizeable class diagrams. So for clarity we will only consider a subset
+of the coffees: Espresso, Espresso Con Panna, Café Late, Cappuccino and Café
+Mocha. We'll include 2 extras - whipped cream ("whipped") and an extra shot of
+espresso; and three changes - decaf, steamed milk ("wet") and foamed milk
+("dry").
+
+Class for Each Combination
+=======================================================================
+
+One solution is to create an individual class for every combination. Each class
+describes the drink and is responsible for the cost etc. The resulting menu is
+huge, and a part of the class diagram would look something like this:
+
+.. image:: _images/coffeeExplosion.*
+
+The key to using this method is to find the particular combination you want.
+So, once you've found the drink you would like, here is how you would use it, as
+shown in the **CoffeeShop** class in the following code::
+
+    # Decorator/nodecorators/CoffeeShop.py
+    # Coffee example with no decorators
+
+    class Espresso: pass
+    class DoubleEspresso: pass
+    class EspressoConPanna: pass
+
+    class Cappuccino:
+        def __init__(self):
+            self.cost = 1
+            self.description = "Cappucino"
+        def getCost(self):
+            return self.cost
+        def getDescription(self):
+            return self.description
+
+    class CappuccinoDecaf: pass
+    class CappuccinoDecafWhipped: pass
+    class CappuccinoDry: pass
+    class CappuccinoDryWhipped: pass
+    class CappuccinoExtraEspresso: pass
+    class CappuccinoExtraEspressoWhipped: pass
+    class CappuccinoWhipped: pass
+
+    class CafeMocha: pass
+    class CafeMochaDecaf: pass
+    class CafeMochaDecafWhipped:
+        def __init__(self):
+            self.cost = 1.25
+            self.description = \
+              "Cafe Mocha decaf whipped cream"
+        def getCost(self):
+            return self.cost
+        def getDescription(self):
+            return self.description
+
+    class CafeMochaExtraEspresso: pass
+    class CafeMochaExtraEspressoWhipped: pass
+    class CafeMochaWet: pass
+    class CafeMochaWetWhipped: pass
+    class CafeMochaWhipped: pass
+
+    class CafeLatte: pass
+    class CafeLatteDecaf: pass
+    class CafeLatteDecafWhipped: pass
+    class CafeLatteExtraEspresso: pass
+    class CafeLatteExtraEspressoWhipped: pass
+    class CafeLatteWet: pass
+    class CafeLatteWetWhipped: pass
+    class CafeLatteWhipped: pass
+
+    cappuccino = Cappuccino()
+    print((cappuccino.getDescription() + ": $" +
+      `cappuccino.getCost()`))
+
+    cafeMocha = CafeMochaDecafWhipped()
+    print((cafeMocha.getDescription()
+      + ": $" + `cafeMocha.getCost()`))
+
+
+
+And here is the corresponding output::
+
+    Cappucino: $1.0
+    Cafe Mocha decaf whipped cream: $1.25
+
+You can see that creating the particular combination you want is easy, since you
+are just creating an instance of a class. However, there are a number of
+problems with this approach. Firstly, the combinations are fixed statically so
+that any combination a customer may wish to order needs to be created up front.
+Secondly, the resulting menu is so huge that finding your particular combination
+is difficult and time consuming.
+
+The Decorator Approach
+=======================================================================
+
+Another approach would be to break the drinks down into the various components
+such as espresso and foamed milk, and then let the customer combine the
+components to describe a particular coffee.
+
+In order to do this programmatically, we use the Decorator pattern.  A Decorator
+adds responsibility to a component by wrapping it, but the Decorator conforms to
+the interface of the component it encloses, so the wrapping is transparent.
+Decorators can also be nested without the loss of this transparency.
+
+.. image:: _images/decoratedCoffee.*
+
+
+Methods invoked on the Decorator can in turn invoke methods in the component,
+and can of course perform processing before or after the invocation.
+
+So if we added **getTotalCost()** and **getDescription()** methods to the
+**DrinkComponent** interface, an Espresso looks like this::
+
+    # Decorator/alldecorators/EspressoDecorator.py
+
+    class Espresso(Decorator):
+        cost = 0.75f
+        description = " espresso"
+        def __init__(DrinkComponent):
+            Decorator.__init__(self, component)
+
+        def getTotalCost(self):
+            return self.component.getTotalCost() + cost
+
+        def getDescription(self):
+            return self.component.getDescription() +
+                description
+
+
+You combine the components to create a drink as follows, as shown in the code
+below::
+
+    # Decorator/alldecorators/CoffeeShop.py
+    # Coffee example using decorators
+
+    class DrinkComponent:
+        def getDescription(self):
+            return self.__class__.__name__
+        def getTotalCost(self):
+            return self.__class__.cost
+
+    class Mug(DrinkComponent):
+        cost = 0.0
+
+    class Decorator(DrinkComponent):
+        def __init__(self, drinkComponent):
+            self.component = drinkComponent
+        def getTotalCost(self):
+            return self.component.getTotalCost() + \
+              DrinkComponent.getTotalCost(self)
+        def getDescription(self):
+            return self.component.getDescription() + \
+              ' ' + DrinkComponent.getDescription(self)
+
+    class Espresso(Decorator):
+        cost = 0.75
+        def __init__(self, drinkComponent):
+            Decorator.__init__(self, drinkComponent)
+
+    class Decaf(Decorator):
+        cost = 0.0
+        def __init__(self, drinkComponent):
+            Decorator.__init__(self, drinkComponent)
+
+    class FoamedMilk(Decorator):
+        cost = 0.25
+        def __init__(self, drinkComponent):
+            Decorator.__init__(self, drinkComponent)
+
+    class SteamedMilk(Decorator):
+        cost = 0.25
+        def __init__(self, drinkComponent):
+            Decorator.__init__(self, drinkComponent)
+
+    class Whipped(Decorator):
+        cost = 0.25
+        def __init__(self, drinkComponent):
+            Decorator.__init__(self, drinkComponent)
+
+    class Chocolate(Decorator):
+        cost = 0.25
+        def __init__(self, drinkComponent):
+            Decorator.__init__(self, drinkComponent)
+
+    cappuccino = Espresso(FoamedMilk(Mug()))
+    print(cappuccino.getDescription().strip() + \)
+      ": $" + `cappuccino.getTotalCost()`
+
+    cafeMocha = Espresso(SteamedMilk(Chocolate(
+      Whipped(Decaf(Mug())))))
+
+    print(cafeMocha.getDescription().strip() + \)
+      ": $" + `cafeMocha.getTotalCost()`
+
+
+
+This approach would certainly provide the most flexibility and the smallest
+menu. You have a small number of components to choose from, but assembling the
+description of the coffee then becomes rather arduous.
+
+If you want to describe a plain cappuccino, you create it with::
+
+    plainCap = Espresso(FoamedMilk(Mug()))
+
+Creating a decaf Cafe Mocha with whipped cream requires an even longer
+description.
+
+Compromise
+=======================================================================
+
+The previous approach takes too long to describe a coffee. There will also be
+certain combinations that you will describe regularly, and it would be
+convenient to have a quick way of describing them.
+
+The 3rd approach is a mixture of the first 2 approaches, and combines
+flexibility with ease of use. This compromise is achieved by creating a
+reasonably sized menu of basic selections, which would often work exactly as
+they are, but if you wanted to decorate them (whipped cream, decaf etc.) then
+you would use decorators to make the modifications. This is the type of menu you
+are presented with in most coffee shops.
+
+.. image:: _images/compromiseDecoration.*
+
+Here is how to create a basic selection, as well as a decorated selection::
+
+    # Decorator/compromise/CoffeeShop.py
+    # Coffee example with a compromise of basic
+    # combinations and decorators
+
+    class DrinkComponent:
+        def getDescription(self):
+            return self.__class__.__name__
+        def getTotalCost(self):
+            return self.__class__.cost
+
+    class Espresso(DrinkComponent):
+        cost = 0.75
+
+    class EspressoConPanna(DrinkComponent):
+        cost = 1.0
+
+    class Cappuccino(DrinkComponent):
+        cost = 1.0
+
+    class CafeLatte(DrinkComponent):
+        cost = 1.0
+
+    class CafeMocha(DrinkComponent):
+        cost = 1.25
+
+    class Decorator(DrinkComponent):
+        def __init__(self, drinkComponent):
+            self.component = drinkComponent
+        def getTotalCost(self):
+            return self.component.getTotalCost() + \
+              DrinkComponent.getTotalCost(self)
+        def getDescription(self):
+            return self.component.getDescription() + \
+              ' ' + DrinkComponent.getDescription(self)
+
+    class ExtraEspresso(Decorator):
+        cost = 0.75
+        def __init__(self, drinkComponent):
+            Decorator.__init__(self, drinkComponent)
+
+    class Whipped(Decorator):
+        cost = 0.50
+        def __init__(self, drinkComponent):
+            Decorator.__init__(self, drinkComponent)
+
+    class Decaf(Decorator):
+        cost = 0.0
+        def __init__(self, drinkComponent):
+            Decorator.__init__(self, drinkComponent)
+
+    class Dry(Decorator):
+        cost = 0.0
+        def __init__(self, drinkComponent):
+            Decorator.__init__(self, drinkComponent)
+
+    class Wet(Decorator):
+        cost = 0.0
+        def __init__(self, drinkComponent):
+            Decorator.__init__(self, drinkComponent)
+
+    cappuccino = Cappuccino()
+    print(cappuccino.getDescription() + ": $" + \)
+      `cappuccino.getTotalCost()`
+
+    cafeMocha = Whipped(Decaf(CafeMocha()))
+    print(cafeMocha.getDescription() + ": $" + \)
+      `cafeMocha.getTotalCost()`
+
+
+
+You can see that creating a basic selection is quick and easy, which makes sense
+since they will be described regularly.  Describing a decorated drink is more
+work than when using a class per combination, but clearly less work than when
+only using decorators.
+
+The final result is not too many classes, but not too many decorators either.
+Most of the time it's possible to get away without using any decorators at all,
+so we have the benefits of both approaches.
+
+Other Considerations
+=======================================================================
+
+What happens if we decide to change the menu at a later stage, such as by adding
+a new type of drink? If we had used the class per combination approach, the
+effect of adding an extra such as syrup would be an exponential growth in the
+number of classes. However, the implications to the all decorator or compromise
+approaches are the same - one extra class is created.
+
+How about the effect of changing the cost of steamed milk and foamed milk, when
+the price of milk goes up? Having a class for each combination means that you
+need to change a method in each class, and thus maintain many classes. By using
+decorators, maintenance is reduced by defining the logic in one place.
+
+Exercises
+=======================================================================
+
+#.  Add a Syrup class to the decorator approach described above. Then create a
+    Café Latte (you'll need to use steamed milk with an espresso) with syrup.
+
+#.  Repeat Exercise 1 for the compromise approach.
+
+#.  Implement the decorator pattern to create a Pizza restaurant, which has a
+    set menu of choices as well as the option to design your own pizza.  Follow
+    the compromise approach to create a menu consisting of a Margherita,
+    Hawaiian, Regina, and Vegetarian pizzas, with toppings (decorators) of
+    Garlic, Olives, Spinach, Avocado, Feta and Pepperdews. Create a Hawaiian
+    pizza, as well as a Margherita decorated with Spinach, Feta, Pepperdews and
+    Olives.

File src/DeveloperGuide.rst

     comparatively)... make any changes.... repeat....
 
 #.  ``hg ci`` without a message, it brought up an editor with a list of all
-    changed files - so you can comment individually.
+    changed files - so you can comment individually.
+
+Emacs for Editing Restructured Text
+===============================================================================
+
+If you want an editing system with support for restructured text, one choice is
+the free text editor *emacs*, which has an add-on mode for restructured text.
+Emacs has a long and venerable history, and is an extremely powerful editor.
+Emacs also has versions that are customized for operating systems to make it
+much more familiar.
+
+Here's a `simple introduction to emacs <http://lowfatlinux.com/linux-editor-emacs.html>`_
+and a `useful introductory help guide <http://www.linuxhelp.net/guides/emacs/>`_.
+For Windows, there's `a special FAQ <http://www.gnu.org/software/emacs/windows/ntemacs.html>`_.
+
+**Mac OSX**: `Aquamacs <http://aquamacs.org/>`_ looks and feels like a native
+Mac application.
+
+**Windows**: You can download the latest windows installer `here (choose the
+highest numbered zip file with "bin" in the name) <http://ftp.gnu.org/pub/gnu/emacs/windows/>`_.
+`This blog <http://www.arunrocks.com/blog/archives/2008/02/20/5-indespensible-tips-for-emacs-on-windows/>`_
+gives useful tips to make emacs on Windows even friendlier (in particular, it
+puts emacs on the right-click menu and improves the startup settings).
+
+**Linux**: It's virtually guaranteed that you already have emacs preinstalled
+on your Linux distribution, which you can start from a command prompt. However,
+there may also be more "windowy" versions that you can install separately.
+
+.. ToDo:: Someone who knows more about emacs for Linux please add more specific information the windowed version(s).
+
+Finally, `here's the documentation for installing and using the emacs
+restructured-text mode <http://docutils.sourceforge.net/docs/user/emacs.html>`_.
+The elisp code it refers to is in the file 'rst.el <http://docutils.sourceforge.net/tools/editors/emacs/rst.el>`_.
+
+To customize your emacs, you need to open the ``.emacs`` file. The above Windows
+FAQ tells you how to put your ``.emacs`` file somewhere else, but the easiest
+thing to do is just open emacs and inside it type ``C-x C-f ~/.emacs``, which
+will open your default ``.emacs`` file.

File src/Factory.rst

+
+
+********************************************************************************
+Factory: Encapsulating Object Creation
+********************************************************************************
+
+When you discover that you need to add new types to a system, the most sensible
+first step is to use polymorphism to create a common interface to those new
+types. This separates the rest of the code in your system from the knowledge of
+the specific types that you are adding. New types may be added without
+disturbing existing code ... or so it seems. At first it would appear that the
+only place you need to change the code in such a design is the place where you
+inherit a new type, but this is not quite true. You must still create an object
+of your new type, and at the point of creation you must specify the exact
+constructor to use. Thus, if the code that creates objects is distributed
+throughout your application, you have the same problem when adding new types-you
+must still chase down all the points of your code where type matters. It happens
+to be the *creation* of the type that matters in this case rather than the *use*
+of the type (which is taken care of by polymorphism), but the effect is the
+same: adding a new type can cause problems.
+
+The solution is to force the creation of objects to occur through a common
+*factory* rather than to allow the creational code to be spread throughout your
+system. If all the code in your program must go through this factory whenever it
+needs to create one of your objects, then all you must do when you add a new
+object is to modify the factory.
+
+Since every object-oriented program creates objects, and since it's very likely
+you will extend your program by adding new types, I suspect that factories may
+be the most universally useful kinds of design patterns.
+
+Simple Factory Method
+=======================================================================
+
+As an example, let's revisit the **Shape** system.
+
+One approach is to make the factory a **static** method of the base class::
+
+    # Factory/shapefact1/ShapeFactory1.py
+    # A simple static factory method.
+    from __future__ import generators
+    import random
+
+    class Shape(object):
+        # Create based on class name:
+        def factory(type):
+            #return eval(type + "()")
+            if type == "Circle": return Circle()
+            if type == "Square": return Square()
+            assert 0, "Bad shape creation: " + type
+        factory = staticmethod(factory)
+
+    class Circle(Shape):
+        def draw(self): print("Circle.draw")
+        def erase(self): print("Circle.erase")
+
+    class Square(Shape):
+        def draw(self): print("Square.draw")
+        def erase(self): print("Square.erase")
+
+    # Generate shape name strings:
+    def shapeNameGen(n):
+        types = Shape.__subclasses__()
+        for i in range(n):
+            yield random.choice(types).__name__
+
+    shapes = \
+      [ Shape.factory(i) for i in shapeNameGen(7)]
+
+    for shape in shapes:
+        shape.draw()
+        shape.erase()
+
+
+
+The **factory( )** takes an argument that allows it to determine what type of
+**Shape** to create; it happens to be a **String** in this case but it could be
+any set of data. The **factory( )** is now the only other code in the system
+that needs to be changed when a new type of **Shape** is added (the
+initialization data for the objects will presumably come from somewhere outside
+the system, and not be a hard-coded array as in the above example).
+
+Note that this example also shows the new Python 2.2 **staticmethod( )**
+technique for creating static methods in a class.
+
+I have also used a tool which is new in Python 2.2 called a *generator*. A
+generator is a special case of a factory: it's a factory that takes no arguments
+in order to create a new object. Normally you hand some information to a factory
+in order to tell it what kind of object to create and how to create it, but a
+generator has some kind of internal algorithm that tells it what and how to
+build. It "generates out of thin air" rather than being told what to create.
+
+Now, this may not look consistent with the code you see above::
+
+    for i in shapeNameGen(7)
+
+looks like there's an initialization taking place. This is where a generator is
+a bit strange - when you call a function that contains a **yield** statement
+(**yield** is a new keyword that determines that a function is a generator),
+that function actually returns a generator object that has an iterator. This
+iterator is implicitly used in the **for** statement above, so it appears that
+you are iterating through the generator function, not what it returns. This was
+done for convenience of use.
+
+Thus, the code that you write is actually a kind of factory, that creates the
+generator objects that do the actual generation. You can use the generator
+explicitly if you want, for example::
+
+    gen = shapeNameGen(7)
+    print(gen.next())
+
+So **next( )** is the iterator method that's actually called to generate the
+next object, and it takes no arguments. **shapeNameGen( )** is the factory, and
+**gen** is the generator.
+
+Inside the generator-factory, you can see the call to **__subclasses__( )**,
+which produces a list of references to each of the subclasses of **Shape**
+(which must be inherited from **object** for this to work). You should be aware,
+however, that this only works for the first level of inheritance from **Item**,
+so if you were to inherit a new class from **Circle**, it wouldn't show up in
+the list generated by **__subclasses__( )**. If you need to create a deeper
+hierarchy this way, you must recurse the **__subclasses__( )** list.
+
+Also note that in **shapeNameGen( )** the statement::
+
+    types = Shape.__subclasses__()
+
+Is only executed when the generator object is produced; each time the **next(
+)** method of this generator object is called (which, as noted above, may happen
+implicitly), only the code in the **for** loop will be executed, so you don't
+have wasteful execution (as you would if this were an ordinary function).
+
+Preventing direct creation
+--------------------------------------------------------------------------------
+
+To disallow direct access to the classes, you can nest the classes within the
+factory method, like this::
+
+    # Factory/shapefact1/NestedShapeFactory.py
+    import random
+
+    class Shape(object):
+        types = []
+
+    def factory(type):
+        class Circle(Shape):
+            def draw(self): print("Circle.draw")
+            def erase(self): print("Circle.erase")
+
+        class Square(Shape):
+            def draw(self): print("Square.draw")
+            def erase(self): print("Square.erase")
+
+        if type == "Circle": return Circle()
+        if type == "Square": return Square()
+        assert 0, "Bad shape creation: " + type
+
+    def shapeNameGen(n):
+        for i in range(n):
+            yield factory(random.choice(["Circle", "Square"]))
+
+    # Circle() # Not defined
+
+    for shape in shapeNameGen(7):
+        shape.draw()
+        shape.erase()
+
+
+
+
+Polymorphic Factories
+=======================================================================
+
+The static **factory( )** method in the previous example forces all the creation
+operations to be focused in one spot, so that's the only place you need to
+change the code. This is certainly a reasonable solution, as it throws a box
+around the process of creating objects. However, the *Design Patterns* book
+emphasizes that the reason for the *Factory Method* pattern is so that different
+types of factories can be subclassed from the basic factory (the above design is
+mentioned as a special case). However, the book does not provide an example, but
+instead just repeats the example used for the *Abstract Factory* (you'll see an
+example of this in the next section). Here is **ShapeFactory1.py** modified so
+the factory methods are in a separate class as virtual functions. Notice also
+that the specific **Shape** classes are dynamically loaded on demand::
+
+    # Factory/shapefact2/ShapeFactory2.py
+    # Polymorphic factory methods.
+    from __future__ import generators
+    import random
+
+    class ShapeFactory:
+        factories = {}
+        def addFactory(id, shapeFactory):
+            ShapeFactory.factories.put[id] = shapeFactory
+        addFactory = staticmethod(addFactory)
+        # A Template Method:
+        def createShape(id):
+            if not ShapeFactory.factories.has_key(id):
+                ShapeFactory.factories[id] = \
+                  eval(id + '.Factory()')
+            return ShapeFactory.factories[id].create()
+        createShape = staticmethod(createShape)
+
+    class Shape(object): pass
+
+    class Circle(Shape):
+        def draw(self): print("Circle.draw")
+        def erase(self): print("Circle.erase")
+        class Factory:
+            def create(self): return Circle()
+
+    class Square(Shape):
+        def draw(self):
+            print("Square.draw")
+        def erase(self):
+            print("Square.erase")
+        class Factory:
+            def create(self): return Square()
+
+    def shapeNameGen(n):
+        types = Shape.__subclasses__()
+        for i in range(n):
+            yield random.choice(types).__name__
+
+    shapes = [ ShapeFactory.createShape(i)
+               for i in shapeNameGen(7)]
+
+    for shape in shapes:
+        shape.draw()
+        shape.erase()
+
+
+
+Now the factory method appears in its own class, **ShapeFactory**, as the
+**create( )** method. The different types of shapes must each create their own
+factory with a **create( )** method to create an object of their own type. The
+actual creation of shapes is performed by calling **ShapeFactory.createShape(
+)**, which is a static method that uses the dictionary in **ShapeFactory** to
+find the appropriate factory object based on an identifier that you pass it. The
+factory is immediately used to create the shape object, but you could imagine a
+more complex problem where the appropriate factory object is returned and then
+used by the caller to create an object in a more sophisticated way. However, it
+seems that much of the time you don't need the intricacies of the polymorphic
+factory method, and a single static method in the base class (as shown in
+**ShapeFactory1.py**) will work fine.
+
+Notice that the **ShapeFactory** must be initialized by loading its dictionary
+with factory objects, which takes place in the static initialization clause of
+each of the shape implementations.
+
+Abstract Factories
+=======================================================================
+
+The *Abstract Factory* pattern looks like the factory objects we've seen
+previously, with not one but several factory methods. Each of the factory
+methods creates a different kind of object. The idea is that at the point of
+creation of the factory object, you decide how all the objects created by that
+factory will be used. The example given in *Design Patterns* implements
+portability across various graphical user interfaces (GUIs): you create a
+factory object appropriate to the GUI that you're working with, and from then on
+when you ask it for a menu, button, slider, etc. it will automatically create
+the appropriate version of that item for the GUI. Thus you're able to isolate,
+in one place, the effect of changing from one GUI to another.
+
+As another example suppose you are creating a general-purpose gaming environment
+and you want to be able to support different types of games. Here's how it might
+look using an abstract factory::
+
+    # Factory/Games.py
+    # An example of the Abstract Factory pattern.
+
+    class Obstacle:
+        def action(self): pass
+
+    class Character:
+        def interactWith(self, obstacle): pass
+
+    class Kitty(Character):
+        def interactWith(self, obstacle):
+            print("Kitty has encountered a",
+            obstacle.action())
+
+    class KungFuGuy(Character):
+        def interactWith(self, obstacle):
+            print("KungFuGuy now battles a",
+            obstacle.action())
+
+    class Puzzle(Obstacle):
+        def action(self):
+            print("Puzzle")
+
+    class NastyWeapon(Obstacle):
+        def action(self):
+            print("NastyWeapon")
+
+    # The Abstract Factory:
+    class GameElementFactory:
+        def makeCharacter(self): pass
+        def makeObstacle(self): pass
+
+    # Concrete factories:
+    class KittiesAndPuzzles(GameElementFactory):
+        def makeCharacter(self): return Kitty()
+        def makeObstacle(self): return Puzzle()
+
+    class KillAndDismember(GameElementFactory):
+        def makeCharacter(self): return KungFuGuy()
+        def makeObstacle(self): return NastyWeapon()
+
+    class GameEnvironment:
+        def __init__(self, factory):
+            self.factory = factory
+            self.p = factory.makeCharacter()
+            self.ob = factory.makeObstacle()
+        def play(self):
+            self.p.interactWith(self.ob)
+
+    g1 = GameEnvironment(KittiesAndPuzzles())
+    g2 = GameEnvironment(KillAndDismember())
+    g1.play()
+    g2.play()
+
+
+
+In this environment, **Character** objects interact with **Obstacle** objects,
+but there are different types of Characters and obstacles depending on what kind
+of game you're playing. You determine the kind of game by choosing a particular
+**GameElementFactory**, and then the **GameEnvironment** controls the setup and
+play of the game. In this example, the setup and play is very simple, but those
+activities (the *initial conditions* and the *state change*) can determine much
+of the game's outcome. Here, **GameEnvironment** is not designed to be
+inherited, although it could very possibly make sense to do that.
+
+This also contains examples of *Double Dispatching* and the *Factory Method*,
+both of which will be explained later.
+
+Of course, the above scaffolding of **Obstacle**, **Character** and
+**GameElementFactory** (which was translated from the Java version of this
+example) is unnecessary - it's only required for languages that have static type
+checking. As long as the concrete Python classes follow the form of the required
+classes, we don't need any base classes::
+
+    # Factory/Games2.py
+    # Simplified Abstract Factory.
+
+    class Kitty:
+        def interactWith(self, obstacle):
+            print("Kitty has encountered a",
+            obstacle.action())
+
+    class KungFuGuy:
+        def interactWith(self, obstacle):
+            print("KungFuGuy now battles a",
+            obstacle.action())
+
+    class Puzzle:
+        def action(self): print("Puzzle")
+
+    class NastyWeapon:
+        def action(self): print("NastyWeapon")
+
+    # Concrete factories:
+    class KittiesAndPuzzles:
+        def makeCharacter(self): return Kitty()
+        def makeObstacle(self): return Puzzle()
+
+    class KillAndDismember:
+        def makeCharacter(self): return KungFuGuy()
+        def makeObstacle(self): return NastyWeapon()
+
+    class GameEnvironment:
+        def __init__(self, factory):
+            self.factory = factory
+            self.p = factory.makeCharacter()
+            self.ob = factory.makeObstacle()
+        def play(self):
+            self.p.interactWith(self.ob)
+
+    g1 = GameEnvironment(KittiesAndPuzzles())
+    g2 = GameEnvironment(KillAndDismember())
+    g1.play()
+    g2.play()
+
+
+Another way to put this is that all inheritance in Python is implementation
+inheritance; since Python does its type-checking at runtime, there's no need to
+use interface inheritance so that you can upcast to the base type.
+
+You might want to study the two examples for comparison, however. Does the first
+one add enough useful information about the pattern that it's worth keeping some
+aspect of it? Perhaps all you need is "tagging classes" like this::
+
+    class Obstacle: pass
+    class Character: pass
+    class GameElementFactory: pass
+
+Then the inheritance serves only to indicate the type of the derived classes.
+
+Exercises
+=======================================================================
+
+#.  Add a class **Triangle** to **ShapeFactory1.py**
+
+#.  Add a class **Triangle** to **ShapeFactory2.py**
+
+#.  Add a new type of **GameEnvironment** called **GnomesAndFairies** to
+    **GameEnvironment.py**
+
+#.  Modify **ShapeFactory2.py** so that it uses an *Abstract Factory* to create
+    different sets of shapes (for example, one particular type of factory object
+    creates "thick shapes," another creates "thin shapes," but each factory
+    object can create all the shapes: circles, squares, triangles etc.).
+
+
+

File src/Fronting.rst

+
+********************************************************************************
+Fronting for an Implementation
+********************************************************************************
+
+Both *Proxy* and *State* provide a surrogate class that you use in your code;
+the real class that does the work is hidden behind this surrogate class. When
+you call a method in the surrogate, it simply turns around and calls the method
+in the implementing class. These two patterns are so similar that the *Proxy* is
+simply a special case of *State*. One is tempted to just lump the two together
+into a pattern called *Surrogate*, but the term "proxy" has a long-standing and
+specialized meaning, which probably explains the reason for the two different
+patterns.
+
+The basic idea is simple: from a base class, the surrogate is derived along with
+the class or classes that provide the actual implementation:
+
+..  image:: _images/surrogate.*
+
+
+When a surrogate object is created, it is given an implementation to which to
+send all of the method calls.
+
+Structurally, the difference between *Proxy* and *State* is simple: a *Proxy*
+has only one implementation, while *State* has more than one. The application of
+the patterns is considered (in *Design Patterns*) to be distinct: *Proxy* is
+used to control access to its implementation, while *State* allows you to change
+the implementation dynamically. However, if you expand your notion of
+"controlling access to implementation" then the two fit neatly together.
+
+Proxy
+=======================================================================
+
+If we implement *Proxy* by following the above diagram, it looks like this::
+
+    # Fronting/ProxyDemo.py
+    # Simple demonstration of the Proxy pattern.
+
+    class Implementation:
+        def f(self):
+            print("Implementation.f()")
+        def g(self):
+            print("Implementation.g()")
+        def h(self):
+            print("Implementation.h()")
+
+    class Proxy:
+        def __init__(self):
+            self.__implementation = Implementation()
+        # Pass method calls to the implementation:
+        def f(self): self.__implementation.f()
+        def g(self): self.__implementation.g()
+        def h(self): self.__implementation.h()
+
+    p = Proxy()
+    p.f(); p.g(); p.h()
+
+It isn't necessary that **Implementation** have the same interface as **Proxy**;
+as long as **Proxy** is somehow "speaking for" the class that it is referring
+method calls to then the basic idea is satisfied (note that this statement is at
+odds with the definition for Proxy in GoF). However, it is convenient to have a
+common interface so that **Implementation** is forced to fulfill all the methods
+that **Proxy** needs to call.
+
+Of course, in Python we have a delegation mechanism built in, so it makes the
+**Proxy** even simpler to implement::
+
+    # Fronting/ProxyDemo2.py
+    # Simple demonstration of the Proxy pattern.
+
+    class Implementation2:
+        def f(self):
+            print("Implementation.f()")
+        def g(self):
+            print("Implementation.g()")
+        def h(self):
+            print("Implementation.h()")
+
+    class Proxy2:
+        def __init__(self):
+            self.__implementation = Implementation2()
+        def __getattr__(self, name):
+            return getattr(self.__implementation, name)
+
+    p = Proxy2()
+    p.f(); p.g(); p.h();
+
+
+The beauty of using **__getattr__( )** is that **Proxy2** is completely generic,
+and not tied to any particular implementation (in Java, a rather complicated
+"dynamic proxy" has been invented to accomplish this same thing).
+
+State
+=======================================================================
+
+The *State* pattern adds more implementations to *Proxy*, along with a way to
+switch from one implementation to another during the lifetime of the surrogate::
+
+    # Fronting/StateDemo.py
+    # Simple demonstration of the State pattern.
+
+    class State_d:
+        def __init__(self, imp):
+            self.__implementation = imp
+        def changeImp(self, newImp):
+            self.__implementation = newImp
+        # Delegate calls to the implementation:
+        def __getattr__(self, name):
+            return getattr(self.__implementation, name)
+
+    class Implementation1:
+        def f(self):
+            print("Fiddle de dum, Fiddle de dee,")
+        def g(self):
+            print("Eric the half a bee.")
+        def h(self):
+            print("Ho ho ho, tee hee hee,")
+
+    class Implementation2:
+        def f(self):
+            print("We're Knights of the Round Table.")
+        def g(self):
+            print("We dance whene'er we're able.")
+        def h(self):
+            print("We do routines and chorus scenes")
+
+    def run(b):
+        b.f()
+        b.g()
+        b.h()
+        b.g()
+
+    b = State_d(Implementation1())
+    run(b)
+    b.changeImp(Implementation2())
+    run(b)
+
+
+
+You can see that the first implementation is used for a bit, then the second
+implementation is swapped in and that is used.
+
+The difference between *Proxy* and *State* is in the problems that are solved.
+The common uses for *Proxy* as described in *Design Patterns* are:
+
+#.  **Remote proxy**. This proxies for an object in a different address space. A
+    remote proxy is created for you automatically by the RMI compiler **rmic**
+    as it creates stubs and skeletons.
+
+#.  **Virtual proxy**. This provides "lazy initialization" to create expensive
+    objects on demand.
+
+#.  **Protection proxy**. Used when you don't want the client programmer to have
+    full access to the proxied object.
+
+#.  **Smart reference**. To add additional actions when the proxied object is
+    accessed. For example, or to keep track of the number of references that are
+    held for a particular object, in order to implement the *copy-on-write*
+    idiom and prevent object aliasing. A simpler example is keeping track of the
+    number of calls to a particular method.
+
+You could look at a Python reference as a kind of protection proxy, since it
+controls access to the actual object on the heap (and ensures, for example, that
+you don't use a **null** reference).
+
+[[ Rewrite this: In *Design Patterns*, *Proxy* and *State* are not seen as
+related to each other because the two are given (what I consider arbitrarily)
+different structures. *State*, in particular, uses a separate implementation
+hierarchy but this seems to me to be unnecessary unless you have decided that
+the implementation is not under your control (certainly a possibility, but if
+you own all the code there seems to be no reason not to benefit from the
+elegance and helpfulness of the single base class). In addition, *Proxy* need
+not use the same base class for its implementation, as long as the proxy object
+is controlling access to the object it "fronting" for. Regardless of the
+specifics, in both *Proxy* and *State* a surrogate is passing method calls
+through to an implementation object.]]]
+
+
+

File src/FunctionObjects.rst

+
+********************************************************************************
+Function Objects
+********************************************************************************
+
+In *Advanced C++:Programming Styles And Idioms (Addison-Wesley, 1992)*, Jim
+Coplien coins the term *functor* which is an object whose sole purpose is to
+encapsulate a function (since "functor" has a meaning in mathematics, in this
+book I shall use the more explicit term *function object*). The point is to
+decouple the choice of function to be called from the site where that function
+is called.
+
+This term is mentioned but not used in *Design Patterns*. However, the theme of
+the function object is repeated in a number of patterns in that book.
+
+Command: Choosing the Operation at Runtime
+=======================================================================
+
+This is the function object in its purest sense: a method that's an object. By
+wrapping a method in an object, you can pass it to other methods or objects as a
+parameter, to tell them to perform this particular operation in the process of
+fulfilling your request::
+
+    # FunctionObjects/CommandPattern.py
+
+    class Command:
+        def execute(self): pass
+
+    class Loony(Command):
+        def execute(self):
+            print("You're a loony.")
+
+    class NewBrain(Command):
+        def execute(self):
+            print("You might even need a new brain.")
+
+    class Afford(Command):
+        def execute(self):
+            print("I couldn't afford a whole new brain.")
+
+    # An object that holds commands:
+    class Macro:
+        def __init__(self):
+            self.commands = []
+        def add(self, command):
+            self.commands.append(command)
+        def run(self):
+            for c in self.commands:
+                c.execute()
+
+    macro = Macro()
+    macro.add(Loony())
+    macro.add(NewBrain())
+    macro.add(Afford())
+    macro.run()
+
+
+The primary point of *Command* is to allow you to hand a desired action to a
+method or object. In the above example, this provides a way to queue a set of
+actions to be performed collectively. In this case, it allows you to dynamically
+create new behavior, something you can normally only do by writing new code but
+in the above example could be done by interpreting a script (see the
+*Interpreter* pattern if what you need to do gets very complex).
+
+*Design Patterns* says that "Commands are an object-oriented replacement for
+callbacks." However, I think that the word "back" is an essential part of the
+concept of callbacks. That is, I think a callback actually reaches back to the
+creator of the callback. On the other hand, with a *Command* object you
+typically just create it and hand it to some method or object, and are not
+otherwise connected over time to the *Command* object. That's my take on it,
+anyway. Later in this book, I combine a group of design patterns under the
+heading of "callbacks."
+
+Strategy: Choosing the Algorithm at Runtime
+=======================================================================
+
+*Strategy* appears to be a family of *Command* classes, all inherited from the
+same base. But if you look at *Command*, you'll see that it has the same
+structure: a hierarchy of function objects. The difference is in the way this
+hierarchy is used. As seen in **patternRefactoring:DirList.py**, you use
+*Command* to solve a particular problem-in that case, selecting files from a
+list. The "thing that stays the same" is the body of the method that's being
+called, and the part that varies is isolated in the function object. I would
+hazard to say that *Command* provides flexibility while you're writing the
+program, whereas *Strategy*\'s flexibility is at run time.
+
+*Strategy* also adds a "Context" which can be a surrogate class that controls
+the selection and use of the particular strategy object-just like *State*!
+Here's what it looks like::
+
+    # FunctionObjects/StrategyPattern.py
+
+    # The strategy interface:
+    class FindMinima:
+        # Line is a sequence of points:
+        def algorithm(self, line) : pass
+
+    # The various strategies:
+    class LeastSquares(FindMinima):
+        def algorithm(self, line):
+            return [ 1.1, 2.2 ] # Dummy
+
+    class NewtonsMethod(FindMinima):
+        def algorithm(self, line):
+            return [ 3.3, 4.4 ]  # Dummy
+
+    class Bisection(FindMinima):
+        def algorithm(self, line):
+            return [ 5.5, 6.6 ] # Dummy
+
+    class ConjugateGradient(FindMinima):
+        def algorithm(self, line):
+            return [ 3.3, 4.4 ] # Dummy
+
+    # The "Context" controls the strategy:
+    class MinimaSolver:
+        def __init__(self, strategy):
+            self.strategy = strategy
+
+        def minima(self, line):
+            return self.strategy.algorithm(line)
+
+        def changeAlgorithm(self, newAlgorithm):
+            self.strategy = newAlgorithm
+
+    solver = MinimaSolver(LeastSquares())
+    line = [1.0, 2.0, 1.0, 2.0, -1.0, 3.0, 4.0, 5.0, 4.0]
+    print(solver.minima(line))
+    solver.changeAlgorithm(Bisection())
+    print(solver.minima(line))
+
+
+Note similarity with template method - TM claims distinction that it has more
+than one method to call, does things piecewise. However, it's not unlikely that
+strategy object would have more than one method call; consider Shalloway's order
+fulfullment system with country information in each strategy.
+
+Strategy example from standard Python: **sort( )** takes a second optional
+argument that acts as a comparator object; this is a strategy.
+
+.. note:: A better, real world example is numerical integration, shown here:
+          http://www.rosettacode.org/wiki/Numerical_Integration#Python
+
+Chain of Responsibility
+=======================================================================
+
+*Chain of Responsibility* might be thought of as a dynamic generalization of
+recursion using *Strategy* objects. You make a call, and each *Strategy* in a
+linked sequence tries to satisfy the call. The process ends when one of the
+strategies is successful or the chain ends. In recursion, one method calls
+itself over and over until a termination condition is reached; with *Chain of
+Responsibility*, a method calls itself, which (by moving down the chain of
+*Strategies*) calls a different implementation of the method, etc., until a
+termination condition is reached. The termination condition is either the bottom
+of the chain is reached (in which case a default object is returned; you may or
+may not be able to provide a default result so you must be able to determine the
+success or failure of the chain) or one of the *Strategies* is successful.
+
+Instead of calling a single method to satisfy a request, multiple methods in the
+chain have a chance to satisfy the request, so it has the flavor of an expert
+system. Since the chain is effectively a linked list, it can be dynamically
+created, so you could also think of it as a more general, dynamically-built
+**switch** statement.
+
+In the GoF, there's a fair amount of Thidiscussion of how to create the chain of
+responsibility as a linked list. However, when you look at the pattern it really
+shouldn't matter how the chain is maintained; that's an implementation detail.
+Since GoF was written before the Standard Template Library (STL) was
+incorporated into most C++ compilers, the reason for this is most likely (1)
+there was no list and thus they had to create one and (2) data structures are
+often taught as a fundamental skill in academia, and the idea that data
+structures should be standard tools available with the programming language may
+not have occurred to the GoF authors. I maintain that the implementation of
+*Chain of Responsibility* as a chain (specifically, a linked list) adds nothing
+to the solution and can just as easily be implemented using a standard Python
+list, as shown below. Furthermore, you'll see that I've gone to some effort to
+separate the chain-management parts of the implementation from the various
+*Strategies*, so that the code can be more easily reused.
+
+In **StrategyPattern.py**, above, what you probably want is to automatically
+find a solution. *Chain of Responsibility* provides a way to do this by chaining
+the *Strategy* objects together and providing a mechanism for them to
+automatically recurse through each one in the chain::
+
+    # FunctionObjects/ChainOfResponsibility.py
+
+    # Carry the information into the strategy:
+    class Messenger: pass
+
+    # The Result object carries the result data and
+    # whether the strategy was successful:
+    class Result:
+        def __init__(self):
+            self.succeeded = 0
+        def isSuccessful(self):
+            return self.succeeded
+        def setSuccessful(self, succeeded):
+            self.succeeded = succeeded
+
+    class Strategy:
+        def __call__(messenger): pass
+        def __str__(self):
+            return "Trying " + self.__class__.__name__ \
+              + " algorithm"
+
+    # Manage the movement through the chain and
+    # find a successful result:
+    class ChainLink:
+        def __init__(self, chain, strategy):
+            self.strategy = strategy
+            self.chain = chain
+            self.chain.append(self)
+
+        def next(self):
+            # Where this link is in the chain:
+            location = self.chain.index(self)
+            if not self.end():
+                return self.chain[location + 1]
+
+        def end(self):
+            return (self.chain.index(self) + 1 >=
+                    len(self.chain))
+
+        def __call__(self, messenger):
+            r = self.strategy(messenger)
+            if r.isSuccessful() or self.end(): return r
+            return self.next()(messenger)
+
+    # For this example, the Messenger
+    # and Result can be the same type:
+    class LineData(Result, Messenger):
+        def __init__(self, data):
+            self.data = data
+        def __str__(self): return `self.data`
+
+    class LeastSquares(Strategy):
+        def __call__(self, messenger):
+            print(self)
+            linedata = messenger
+            # [ Actual test/calculation here ]
+            result = LineData([1.1, 2.2]) # Dummy data
+            result.setSuccessful(0)
+            return result
+
+    class NewtonsMethod(Strategy):
+        def __call__(self, messenger):
+            print(self)
+            linedata = messenger
+            # [ Actual test/calculation here ]
+            result = LineData([3.3, 4.4]) # Dummy data
+            result.setSuccessful(0)
+            return result
+
+    class Bisection(Strategy):
+        def __call__(self, messenger):
+            print(self)
+            linedata = messenger
+            # [ Actual test/calculation here ]
+            result = LineData([5.5, 6.6]) # Dummy data
+            result.setSuccessful(1)
+            return result
+
+    class ConjugateGradient(Strategy):
+        def __call__(self, messenger):
+            print(self)
+            linedata = messenger
+            # [ Actual test/calculation here ]
+            result = LineData([7.7, 8.8]) # Dummy data
+            result.setSuccessful(1)
+            return result
+
+    solutions = []
+    ChainLink(solutions, LeastSquares()),
+    ChainLink(solutions, NewtonsMethod()),
+    ChainLink(solutions, Bisection()),
+    ChainLink(solutions, ConjugateGradient())
+
+    line = LineData([
+      1.0, 2.0, 1.0, 2.0, -1.0,
+      3.0, 4.0, 5.0, 4.0
+    ])
+
+    print(solutions[0](line))
+
+
+Exercises
+=======================================================================
+
+#.  Use *Command* in Chapter 3, Exercise 1.
+
+#.  Implement *Chain of Responsibility* to create an "expert system" that solves
+    problems by successively trying one solution after another until one
+    matches. You should be able to dynamically add solutions to the expert
+    system. The test for solution should just be a string match, but when a
+    solution fits, the expert system should return the appropriate type of
+    **ProblemSolver** object. What other pattern/patterns show up here?
+
+.. rubric:: Footnotes
+
+.. [#] In Python, all functions are already objects and so the *Command* pattern
+       is often redundant.
+
+.. [#] *Design Patterns*, Page 235.
+
+

File src/Introduction.rst

+.. -*- mode: rst -*-
 *******************************************************************************
 Introduction
 *******************************************************************************

File src/Iterators.rst

+********************************************************************************
+Iterators: Decoupling Algorithms from Containers
+********************************************************************************
+
+.. note:: This chapter has not had any significant translation yet.
+
+Alexander Stepanov thought for years about the problem of generic programming
+techniques before creating the STL (along with Dave Musser). He came to the
+conclusion that all algorithms are defined on algebraic structures - what we
+would call containers.
+
+In the process, he realized that iterators are central to the use of algorithms,
+because they decouple the algorithms from the specific type of container that
+the algorithm might currently be working with. This means that you can describe
+the algorithm without worrying about the particular sequence it is operating on.
+More generally, *any* code that you write using iterators is decoupled from the
+data structure that the code is manipulating, and thus your code is more general
+and reusable.
+
+The use of iterators also extends your code into the realm of *functional
+programming*, whose objective is to describe *what* a program is doing at every
+step rather than *how* it is doing it. That is, you say "sort" rather than
+describing the sort. The objective of the C++ STL was to provide this *generic
+programming* approach for C++ (how successful this approach will actually be
+remains to be seen).
+
+If you've used containers in Java (and it's hard to write code without using
+them), you've used iterators - in the form of the **Enumeration** in Java
+1.0/1.1 and the **Iterator** in Java 2. So you should already be familiar with
+their general use. If not, see Chapter 9, *Holding Your Objects*, under
+*Iterators* in *Thinking in Java, 3rd edition* (freely downloadable from
+*www.BruceEckel.com*).
+
+Because the Java 2 containers rely heavily on iterators they become excellent
+candidates for generic/functional programming techniques. This chapter will
+explore these techniques by converting the STL algorithms to Java, for use with
+the Java 2 container library.
+
+Type-Safe Iterators
+=======================================================================
+
+In *Thinking in Java*, I show the creation of a type-safe container that will
+only accept a particular type of object. A reader, Linda Pazzaglia, asked for
+the other obvious type-safe component, an iterator that would work with the
+basic **java.util** containers, but impose the constraint that the type of
+objects that it iterates over be of a particular type.
+
+If Java ever includes a template mechanism, this kind of iterator will have the
+added advantage of being able to return a specific type of object, but without
+templates you are forced to return generic **Object**\s, or to require a bit of
+hand-coding for every type that you want to iterate through. I will take the
+former approach.
+
+A second design decision involves the time that the type of object is
+determined. One approach is to take the type of the first object that the
+iterator encounters, but this is problematic because the containers may
+rearrange the objects according to an internal ordering mechanism (such as a
+hash table) and thus you may get different results from one iteration to the
+next. The safe approach is to require the user to establish the type during
+construction of the iterator.
+
+Lastly, how do we build the iterator? We cannot rewrite the existing Java
+library classes that already produce **Enumeration**\s and **Iterator**\s.
+However, we can use the *Decorator* design pattern, and create a class that
+simply wraps the **Enumeration** or **Iterator** that is produced, generating a
+new object that has the iteration behavior that we want (which is, in this case,
+to throw a **RuntimeException** if an incorrect type is encountered) but with
+the same interface as the original **Enumeration** or **Iterator**, so that it
+can be used in the same places (you may argue that this is actually a *Proxy*
+pattern, but it's more likely *Decorator* because of its intent). Here is the
+code::
+
+    # Util/TypedIterator.py
+
+    class TypedIterator(Iterator):
+        def __init__(self, it, type):
+            self.imp = it
+            self.type = type
+
+        def hasNext(self):
+            return imp.hasNext()
+
+        def remove(self): imp.remove()
+        def next(self):
+            obj = imp.next()
+            if(!type.isInstance(obj))
+                throw ClassCastException(
+                  "TypedIterator for type " + type +
+                  " encountered type: " + obj.getClass())
+            return obj
+
+
+
+
+

File src/Jython.rst

+
+
+********************************************************************************
+Jython
+********************************************************************************
+
+.. note:: This chapter has not been brought up-to-date with the current
+          version of Jython.
+
+This chapter looks at the value of crossing language boundaries. It is often
+advantageous to solve a problem using more than one programming language, rather
+than being arbitrarily stuck using a single language. As you'll see in this
+chapter, a problem that is very difficult or tedious to solve in one language
+can often be solved quickly and easily in another. If you can combine the use of
+languages, you can create your product much more quickly and cheaply.
+
+The most straightforward use of this idea is the *Interpreter* design pattern,
+which adds an interpreted language to your program to allow the end user to
+easily customize a solution. In Java, the easiest and most powerful way to do
+this is with *Jython* [#]_, an implementation of the Python language in pure
+Java byte codes.
+
+*Interpreter* solves a particular problem - that of creating a scripting
+language for the user. But sometimes it's just easier and faster to temporarily
+step into another language to solve a particular aspect of your problem. You're
+not creating an interpreter, you're just writing some code in another language.
+Again, Jython is a good example of this, but CORBA also allows you to cross
+language boundaries.
+
+Interpreter Motivation
+=======================================================================
+
+If the application user needs greater run time flexibility, for example to
+create scripts describing the desired behavior of the system, you can use the
+*Interpreter* design pattern. Here, you create and embed a language interpreter
+into your program.
+
+Remember that each design pattern allows one or more factors to change, so it's
+important to first be aware of which factor is changing. Sometimes the end users
+of your application (rather than the programmers of that application) need
+complete flexibility in the way that they configure some aspect of the program.
+That is, they need to do some kind of simple programming. The interpreter
+pattern provides this flexibility by adding a language interpreter.
+
+The problem is that developing your own language and building an interpreter is
+a time-consuming distraction from the process of developing your application.
+You must ask whether you want to finish writing your application or create a new
+language.  The best solution is to reuse code: embed an interpreter that's
+already been built and debugged for you. The Python language can be freely
+embedded into your for-profit application without signing any license agreement,
+paying royalties, or dealing with strings of any kind. There are basically no
+restrictions at all when you're using Python.
+
+For solving Java problems, we will look at a special version of Python called
+Jython. This is generated entirely in Java byte codes, so incorporating it into
+your application is quite simple,  and it's as portable as Java is. It has an
+extremely clean interface with Java: Java can call Python classes, and Python
+can call Java classes.
+
+Python is designed with classes from the ground up and is a truly pure object
+oriented language (both C++ and Java violate purity in various ways). Python
+scales up so that you can create very big programs without losing control of the
+code.
+
+To install Jython, go to `http://jython.sourceforge.net
+<http://jython.sourceforge.net>`_.  The download is a **.class** file, which
+will run an installer when you execute it with Java.  You also need to add
+**jython.jar** to your Java CLASSPATH.
+
+Creating a Language
+=======================================================================
+
+It turns out to be remarkably simple to use Jython to create an interpreted
+language inside your application. Consider the greenhouse controller example
+from Chapter 8 of *Thinking in Java*. This is a situation where you want the end
+user - the person managing the greenhouse - to have configuration control over
+the system, and so a simple scripting language is the ideal solution.
+
+To create the language, we'll simply write a set of Python classes, and the
+constructor of each will add itself to a (static) master list. The common data
+and behavior will be factored into the base class **Event**. Each **Event**
+object will contain an **action** string (for simplicity - in reality, you'd
+have some sort of functionality) and a time when the event is supposed to run.
+The constructor initializes these fields, and then adds the new **Event** object
+to a static list called **events** (defining it in the class, but outside of any
+methods, is what makes it static)::
+
+    # Jython/GreenHouseLanguage.py
+
+    class Event:
+        events = [] # static
+        def __init__(self, action, time):
+            self.action = action
+            self.time = time
+            Event.events.append(self)
+        # Used by sort(). This will cause
+        # comparisons to be based only on time:
+        def __cmp__ (self, other):
+            if self.time < other.time: return -1
+            if self.time > other.time: return 1
+            return 0
+        def run(self):
+            print("%.2f: %s" % (self.time, self.action))
+
+    class LightOn(Event):
+        def __init__(self, time):
+            Event.__init__(self, "Light on", time)
+
+    class LightOff(Event):
+        def __init__(self, time):
+            Event.__init__(self, "Light off", time)
+
+    class WaterOn(Event):
+        def __init__(self, time):
+            Event.__init__(self, "Water on", time)
+
+    class WaterOff(Event):
+        def __init__(self, time):
+            Event.__init__(self, "Water off", time)
+
+    class ThermostatNight(Event):
+        def __init__(self, time):
+            Event.__init__(self,"Thermostat night", time)
+
+    class ThermostatDay(Event):
+        def __init__(self, time):
+            Event.__init__(self, "Thermostat day", time)
+
+    class Bell(Event):
+        def __init__(self, time):
+            Event.__init__(self, "Ring bell", time)
+
+    def run():
+        Event.events.sort();
+        for e in Event.events:
+            e.run()
+
+    # To test, this will be run when you say:
+    # python GreenHouseLanguage.py
+    if __name__ == "__main__":
+        ThermostatNight(5.00)
+        LightOff(2.00)
+        WaterOn(3.30)
+        WaterOff(4.45)
+        LightOn(1.00)
+        ThermostatDay(6.00)
+        Bell(7.00)
+        run()
+
+
+The constructor of each derived class calls the base-class constructor, which
+adds the new object to the list. The **run( )** function sorts the list, which
+automatically uses the **__cmp__( )** method that was defined in **Event** to
+base comparisons on time only. In this example, it only prints out the list, but
+in the real system it would wait for the time of each event to come up and then
+run the event.
+
+The **__main__** section performs a simple test on the classes.
+
+The above file is now a module that can be included in another Python program to
+define all the classes it contains. But instead of an ordinary Python program,
+let's use Jython, inside of Java. This turns out to be remarkably simple: you
+import some Jython classes, create a **PythonInterpreter** object, and cause the
+Python files to be loaded:
+
+.. code-block:: java
+
+    // Jython/GreenHouseController.java
+    package jython;
+    import org.python.util.PythonInterpreter;
+    import org.python.core.*;
+    import junit.framework.*;
+
+    public class
+    GreenHouseController extends TestCase  {
+      PythonInterpreter interp =
+        new PythonInterpreter();
+      public void test() throws PyException  {
+        System.out.println(
+          "Loading GreenHouse Language");
+        interp.execfile("GreenHouseLanguage.py");
+        System.out.println(
+          "Loading GreenHouse Script");
+        interp.execfile("Schedule.ghs");
+        System.out.println(
+          "Executing GreenHouse Script");
+        interp.exec("run()");
+      }
+      public static void
+      main(String[] args) throws PyException  {
+        junit.textui.TestRunner.run(GreenHouseController.class);
+      }
+    }
+
+
+The **PythonInterpreter** object is a complete Python interpreter that accepts
+commands from the Java program. One of these commands is **execfile( )**, which
+tells it to execute all the statements it finds in a particular file. By
+executing **GreenHouseLanguage.py**, all the classes from that file are loaded
+into our **PythonInterpreter** object, and so it now "holds" the greenhouse
+controller language. The **Schedule.ghs** file is the one created by the end
+user to control the greenhouse. Here's an example::
+
+    # Jython/Schedule.ghs
+    Bell(7.00)
+    ThermostatDay(6.00)
+    WaterOn(3.30)
+    LightOn(1.00)
+    ThermostatNight(5.00)
+    LightOff(2.00)
+    WaterOff(4.45)
+
+
+This is the goal of the interpreter design pattern: to make the configuration of
+your program as simple as possible for the end user. With Jython you can achieve
+this with almost no effort at all.
+
+One of the other methods available to the **PythonInterpreter** is **exec( )**,
+which allows you to send a command to the interpreter. Here, the **run( )**
+function is called using **exec( )**.
+
+Controlling the Interpreter
+=======================================================================
+
+The prior example only creates and runs the interpreter using external scripts.
+In the rest of this chapter, we shall look at more sophisticated ways to
+interact with Jython. The simplest way to exercise more control over the
+**PythonInterpreter** object from within Java is to send data to the
+interpreter, and pull data back out.
+
+Putting Data In
+--------------------------------------------------------------------------------
+
+To inject data into your Python program, the **PythonInterpreter** class has a
+deceptively simple method: **set( )**. However, **set( )** takes many different
+data types and performs conversions upon them.  The following example is a
+reasonably thorough exercise of the various **set( )** possibilities, along with
+comments that should give a fairly complete explanation:
+
+.. code-block:: java
+
+    // Jython/PythonInterpreterSetting.java
+    // Passing data from Java to python when using
+    // the PythonInterpreter object.
+    package jython;
+    import org.python.util.PythonInterpreter;
+    import org.python.core.*;
+    import java.util.*;
+    import net.mindview.python.*;
+    import junit.framework.*;
+
+    public class
+    PythonInterpreterSetting extends TestCase  {
+      PythonInterpreter interp =
+        new PythonInterpreter();
+      public void test() throws PyException  {
+        // It automatically converts Strings
+        // into native Python strings:
+        interp.set("a", "This is a test");
+        interp.exec("print(a)");
+        interp.exec("print(a[5:])"); // A slice
+        // It also knows what to do with arrays:
+        String[] s = { "How", "Do", "You", "Do?" };
+        interp.set("b", s);
+        interp.exec("for x in b: print(x[0], x)");
+        // set() only takes Objects, so it can't
+        // figure out primitives. Instead,
+        // you have to use wrappers:
+        interp.set("c", new PyInteger(1));
+        interp.set("d", new PyFloat(2.2));
+        interp.exec("print(c + d)");
+        // You can also use Java's object wrappers:
+        interp.set("c", new Integer(9));
+        interp.set("d", new Float(3.14));
+        interp.exec("print(c + d)");
+        // Define a Python function to print arrays:
+        interp.exec(
+          "def prt(x): \n" +
+          "  print(x)\n" +
+          "  for i in x: \n" +
+          "    print(i,)\n" +
+          "  print(x.__class__)\n");
+        // Arrays are Objects, so it has no trouble
+        // figuring out the types contained in arrays:
+        Object[] types = {
+          new boolean[]{ true, false, false, true },
+          new char[]{ 'a', 'b', 'c', 'd' },
+          new byte[]{ 1, 2, 3, 4 },
+          new int[]{ 10, 20, 30, 40 },
+          new long[]{ 100, 200, 300, 400 },
+          new float[]{ 1.1f, 2.2f, 3.3f, 4.4f },
+          new double[]{ 1.1, 2.2, 3.3, 4.4 },
+        };
+        for(int i = 0; i < types.length; i++) {
+          interp.set("e", types[i]);
+          interp.exec("prt(e)");
+        }
+        // It uses toString() to print Java objects:
+        interp.set("f", new Date());
+        interp.exec("print(f)");
+        // You can pass it a List
+        // and index into it...
+        List x = new ArrayList();
+        for(int i = 0; i < 10; i++)
+            x.add(new Integer(i * 10));
+        interp.set("g", x);
+        interp.exec("print(g)");
+        interp.exec("print(g[1])");
+        // ... But it's not quite smart enough
+        // to treat it as a Python array:
+        interp.exec("print(g.__class__)");
+        // interp.exec("print(g[5:])"); // Fails
+        // must extract the Java array:
+        System.out.println("ArrayList to array:");
+        interp.set("h", x.toArray());
+        interp.exec("print(h.__class__)");
+        interp.exec("print(h[5:])");
+        // Passing in a Map:
+        Map m = new HashMap();
+        m.put(new Integer(1), new Character('a'));
+        m.put(new Integer(3), new Character('b'));
+        m.put(new Integer(5), new Character('c'));
+        m.put(new Integer(7), new Character('d'));
+        m.put(new Integer(11), new Character('e'));
+        System.out.println("m: " + m);
+        interp.set("m", m);
+        interp.exec("print(m, m.__class__," +
+          "m[1], m[1].__class__)");
+        // Not a Python dictionary, so this fails:
+        //! interp.exec("for x in m.keys():" +
+        //!   "print(x, m[x])");
+        // To convert a Map to a Python dictionary,
+        // use net.mindview.python.PyUtil:
+        interp.set("m", PyUtil.toPyDictionary(m));
+        interp.exec("print(m, m.__class__, " +
+          "m[1], m[1].__class__)");
+        interp.exec("for x in m.keys():print(x,m[x])");
+      }
+      public static void
+      main(String[] args) throws PyException  {
+        junit.textui.TestRunner.run(
+          PythonInterpreterSetting.class);
+      }
+    }
+
+
+As usual with Java, the distinction between real objects and primitive types
+causes trouble. In general, if you pass a regular object to **set( )**, it knows
+what to do with it, but if you want to pass in a primitive you must perform a
+conversion. One way to do this is to create a "Py" type, such as **PyInteger**
+or **PyFloat**. but it turns out you can also use Java's own object wrappers
+like **Integer** and **Float**, which is probably going to be a lot easier to
+remember.
+
+Early in the program you'll see an **exec( )** containing the Python statement::
+
+    print(a[5:])
+
+The colon inside the indexing statement indicates a Python *slice*, which
+produces a range of elements from the original array. In this case, it produces
+an array containing the elements from number 5 until the end of the array. You
+could also say '**a[3:5]**' to produce elements 3 through 5, or '**a[:5]**' to
+produce the elements zero through 5. The reason a slice is used in this
+statement is to make sure that the Java **String** has really been converted to
+a Python string, which can also be treated as an array of characters.
+
+You can see that it's possible, using **exec( )**, to create a Python function
+(although it's a bit awkward). The **prt( )** function prints the whole array,
+and then (to make sure it's a real Python array), iterates through each element
+of the array and prints it. Finally, it prints the class of the array, so we can
+see what conversion has taken place (Python not only has run-time type
+information, it also has the equivalent of Java reflection). The **prt( )**
+function is used to print arrays that come from each of the Java primitive
+types.
+
+Although a Java **ArrayList** does pass into the interpreter using **set( )**,
+and you can index into it as if it were an array, trying to create a slice
+fails. To completely convert it into an array, one approach is to simply extract
+a Java array using **toArray( )**, and pass that in. The **set( )** method
+converts it to a **PyArray** - one of the classes provided with Jython - which
+can be treated as a Python array (you can also explicitly create a **PyArray**,
+but this seems unnecessary).
+
+Finally, a **Map** is created and passed directly into the interpreter. While it
+is possible to do simple things like index into the resulting object, it's not a
+real Python dictionary so you can't (for example) call the **keys( )** method.
+There is no straightforward way to convert a Java **Map** into a Python
+dictionary, and so I wrote a utility called **toPyDictionary( )** and made it a
+**static** method of **net.mindview.python.PyUtil**. This also includes
+utilities to extract a Python array into a Java **List**, and a Python
+dictionary into a Java **Map**:
+
+.. code-block:: java
+
+    // Jython/PyUtil.java
+    // PythonInterpreter utilities
+    package net.mindview.python;
+    import org.python.util.PythonInterpreter;
+    import org.python.core.*;
+    import java.util.*;
+
+    public class PyUtil {
+      /** Extract a Python tuple or array into a Java
+      List (which can be converted into other kinds
+      of lists and sets inside Java).
+      @param interp The Python interpreter object
+      @param pyName The id of the python list object
+      */
+      public static List
+      toList(PythonInterpreter interp, String pyName){
+        return new ArrayList(Arrays.asList(
+          (Object[])interp.get(
+            pyName, Object[].class)));
+      }
+      /** Extract a Python dictionary into a Java Map
+      @param interp The Python interpreter object
+      @param pyName The id of the python dictionary
+      */
+      public static Map
+      toMap(PythonInterpreter interp, String pyName){
+        PyList pa = ((PyDictionary)interp.get(
+          pyName)).items();
+        Map map = new HashMap();
+        while(pa.__len__() != 0) {
+          PyTuple po = (PyTuple)pa.pop();
+          Object first = po.__finditem__(0)
+            .__tojava__(Object.class);
+          Object second = po.__finditem__(1)
+            .__tojava__(Object.class);
+          map.put(first, second);
+        }
+        return map;
+      }
+      /** Turn a Java Map into a PyDictionary,
+      suitable for placing into a PythonInterpreter
+      @param map The Java Map object
+      */
+      public static PyDictionary
+      toPyDictionary(Map map) {
+        Map m = new HashMap();
+        Iterator it = map.entrySet().iterator();
+        while(it.hasNext()) {
+          Map.Entry e = (Map.Entry)it.next();
+          m.put(Py.java2py(e.getKey()),
+            Py.java2py(e.getValue()));
+        }
+        // PyDictionary constructor wants a Hashtable:
+        return new PyDictionary(new Hashtable(m));
+      }
+    }
+
+
+Here is the (black-box) unit testing code:
+
+.. code-block:: java
+
+    // Jython/Test.java
+    package net.mindview.python;
+    import org.python.util.PythonInterpreter;
+    import java.util.*;
+    import junit.framework.*;
+
+    public class Test extends TestCase  {
+      PythonInterpreter pi =
+        new PythonInterpreter();
+      public void test1() {
+        pi.exec("tup=('fee','fi','fo','fum','fi')");
+        List lst = PyUtil.toList(pi, "tup");
+        System.out.println(lst);
+        System.out.println(new HashSet(lst));
+      }
+      public void test2() {
+        pi.exec("ints=[1,3,5,7,9,11,13,17,19]");
+        List lst = PyUtil.toList(pi, "ints");
+        System.out.println(lst);
+      }
+      public void test3() {
+        pi.exec("dict = { 1 : 'a', 3 : 'b', " +
+          "5 : 'c', 9 : 'd', 11 : 'e'}");
+        Map mp = PyUtil.toMap(pi, "dict");
+        System.out.println(mp);
+      }
+      public void test4() {