Source

Python 3 Patterns & Idioms / html / FunctionObjects.html

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Function Objects &mdash; Python 3 Patterns, Recipes and Idioms</title>
    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
          URL_ROOT:    '',
          VERSION:     '1.0',
          COLLAPSE_MODINDEX: false,
          FILE_SUFFIX: '.html'
      };
    </script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <link rel="shortcut icon" href="_static/favicon.ico"/>
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="top" title="Python 3 Patterns, Recipes and Idioms" href="index.html" />
    <link rel="next" title="Changing the Interface" href="ChangeInterface.html" />
    <link rel="prev" title="Factory: Encapsulating Object Creation" href="Factory.html" />
  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="ChangeInterface.html" title="Changing the Interface"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="Factory.html" title="Factory: Encapsulating Object Creation"
             accesskey="P">previous</a> |</li>
        <li><a href="index.html">Python 3 Patterns, Recipes and Idioms</a> &raquo;</li>
      </ul>
    </div>
    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  
  <div class="section" id="function-objects">
<h1>Function Objects<a class="headerlink" href="#function-objects" title="Permalink to this headline"></a></h1>
<p>In <em>Advanced C++:Programming Styles And Idioms (Addison-Wesley, 1992)</em>, Jim
Coplien coins the term <em>functor</em> which is an object whose sole purpose is to
encapsulate a function (since &#8220;functor&#8221; has a meaning in mathematics, in this
book I shall use the more explicit term <em>function object</em>). The point is to
decouple the choice of function to be called from the site where that function
is called.</p>
<p>This term is mentioned but not used in <em>Design Patterns</em>. However, the theme of
the function object is repeated in a number of patterns in that book.</p>
<div class="section" id="command-choosing-the-operation-at-runtime">
<h2>Command: Choosing the Operation at Runtime<a class="headerlink" href="#command-choosing-the-operation-at-runtime" title="Permalink to this headline"></a></h2>
<p>This is the function object in its purest sense: a method that&#8217;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:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># FunctionObjects/CommandPattern.py</span>

<span class="k">class</span> <span class="nc">Command</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">execute</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">pass</span>

<span class="k">class</span> <span class="nc">Loony</span><span class="p">(</span><span class="n">Command</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">execute</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">print</span><span class="p">(</span><span class="s">&quot;You&#39;re a loony.&quot;</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">NewBrain</span><span class="p">(</span><span class="n">Command</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">execute</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">print</span><span class="p">(</span><span class="s">&quot;You might even need a new brain.&quot;</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Afford</span><span class="p">(</span><span class="n">Command</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">execute</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">print</span><span class="p">(</span><span class="s">&quot;I couldn&#39;t afford a whole new brain.&quot;</span><span class="p">)</span>

<span class="c"># An object that holds commands:</span>
<span class="k">class</span> <span class="nc">Macro</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">commands</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">command</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">commands</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">command</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">run</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">commands</span><span class="p">:</span>
            <span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">()</span>

<span class="n">macro</span> <span class="o">=</span> <span class="n">Macro</span><span class="p">()</span>
<span class="n">macro</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">Loony</span><span class="p">())</span>
<span class="n">macro</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">NewBrain</span><span class="p">())</span>
<span class="n">macro</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">Afford</span><span class="p">())</span>
<span class="n">macro</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>
</pre></div>
</div>
<p>The primary point of <em>Command</em> 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
<em>Interpreter</em> pattern if what you need to do gets very complex).</p>
<p><em>Design Patterns</em> says that &#8220;Commands are an object-oriented replacement for
callbacks.&#8221; However, I think that the word &#8220;back&#8221; 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 <em>Command</em> object you
typically just create it and hand it to some method or object, and are not
otherwise connected over time to the <em>Command</em> object. That&#8217;s my take on it,
anyway. Later in this book, I combine a group of design patterns under the
heading of &#8220;callbacks.&#8221;</p>
</div>
<div class="section" id="strategy-choosing-the-algorithm-at-runtime">
<h2>Strategy: Choosing the Algorithm at Runtime<a class="headerlink" href="#strategy-choosing-the-algorithm-at-runtime" title="Permalink to this headline"></a></h2>
<p><em>Strategy</em> appears to be a family of <em>Command</em> classes, all inherited from the
same base. But if you look at <em>Command</em>, you&#8217;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 <strong>patternRefactoring:DirList.py</strong>, you use
<em>Command</em> to solve a particular problem-in that case, selecting files from a
list. The &#8220;thing that stays the same&#8221; is the body of the method that&#8217;s being
called, and the part that varies is isolated in the function object. I would
hazard to say that <em>Command</em> provides flexibility while you&#8217;re writing the
program, whereas <em>Strategy</em>&#8216;s flexibility is at run time.</p>
<p><em>Strategy</em> also adds a &#8220;Context&#8221; which can be a surrogate class that controls
the selection and use of the particular strategy object-just like <em>State</em>!
Here&#8217;s what it looks like:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># FunctionObjects/StrategyPattern.py</span>

<span class="c"># The strategy interface:</span>
<span class="k">class</span> <span class="nc">FindMinima</span><span class="p">:</span>
    <span class="c"># Line is a sequence of points:</span>
    <span class="k">def</span> <span class="nf">algorithm</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">line</span><span class="p">)</span> <span class="p">:</span> <span class="k">pass</span>

<span class="c"># The various strategies:</span>
<span class="k">class</span> <span class="nc">LeastSquares</span><span class="p">(</span><span class="n">FindMinima</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">algorithm</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">line</span><span class="p">):</span>
        <span class="k">return</span> <span class="p">[</span> <span class="mf">1.1</span><span class="p">,</span> <span class="mf">2.2</span> <span class="p">]</span> <span class="c"># Dummy</span>

<span class="k">class</span> <span class="nc">NewtonsMethod</span><span class="p">(</span><span class="n">FindMinima</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">algorithm</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">line</span><span class="p">):</span>
        <span class="k">return</span> <span class="p">[</span> <span class="mf">3.3</span><span class="p">,</span> <span class="mf">4.4</span> <span class="p">]</span>  <span class="c"># Dummy</span>

<span class="k">class</span> <span class="nc">Bisection</span><span class="p">(</span><span class="n">FindMinima</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">algorithm</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">line</span><span class="p">):</span>
        <span class="k">return</span> <span class="p">[</span> <span class="mf">5.5</span><span class="p">,</span> <span class="mf">6.6</span> <span class="p">]</span> <span class="c"># Dummy</span>

<span class="k">class</span> <span class="nc">ConjugateGradient</span><span class="p">(</span><span class="n">FindMinima</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">algorithm</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">line</span><span class="p">):</span>
        <span class="k">return</span> <span class="p">[</span> <span class="mf">3.3</span><span class="p">,</span> <span class="mf">4.4</span> <span class="p">]</span> <span class="c"># Dummy</span>

<span class="c"># The &quot;Context&quot; controls the strategy:</span>
<span class="k">class</span> <span class="nc">MinimaSolver</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">strategy</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">strategy</span> <span class="o">=</span> <span class="n">strategy</span>

    <span class="k">def</span> <span class="nf">minima</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">line</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">strategy</span><span class="o">.</span><span class="n">algorithm</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">changeAlgorithm</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">newAlgorithm</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">strategy</span> <span class="o">=</span> <span class="n">newAlgorithm</span>

<span class="n">solver</span> <span class="o">=</span> <span class="n">MinimaSolver</span><span class="p">(</span><span class="n">LeastSquares</span><span class="p">())</span>
<span class="n">line</span> <span class="o">=</span> <span class="p">[</span><span class="mf">1.0</span><span class="p">,</span> <span class="mf">2.0</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">,</span> <span class="mf">2.0</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.0</span><span class="p">,</span> <span class="mf">3.0</span><span class="p">,</span> <span class="mf">4.0</span><span class="p">,</span> <span class="mf">5.0</span><span class="p">,</span> <span class="mf">4.0</span><span class="p">]</span>
<span class="k">print</span><span class="p">(</span><span class="n">solver</span><span class="o">.</span><span class="n">minima</span><span class="p">(</span><span class="n">line</span><span class="p">))</span>
<span class="n">solver</span><span class="o">.</span><span class="n">changeAlgorithm</span><span class="p">(</span><span class="n">Bisection</span><span class="p">())</span>
<span class="k">print</span><span class="p">(</span><span class="n">solver</span><span class="o">.</span><span class="n">minima</span><span class="p">(</span><span class="n">line</span><span class="p">))</span>
</pre></div>
</div>
<p>Note similarity with template method - TM claims distinction that it has more
than one method to call, does things piecewise. However, it&#8217;s not unlikely that
strategy object would have more than one method call; consider Shalloway&#8217;s order
fulfullment system with country information in each strategy.</p>
<p>Strategy example from standard Python: <strong>sort( )</strong> takes a second optional
argument that acts as a comparator object; this is a strategy.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">A better, real world example is numerical integration, shown here:
<a class="reference external" href="http://www.rosettacode.org/wiki/Numerical_Integration#Python">http://www.rosettacode.org/wiki/Numerical_Integration#Python</a></p>
</div>
</div>
<div class="section" id="chain-of-responsibility">
<h2>Chain of Responsibility<a class="headerlink" href="#chain-of-responsibility" title="Permalink to this headline"></a></h2>
<p><em>Chain of Responsibility</em> might be thought of as a dynamic generalization of
recursion using <em>Strategy</em> objects. You make a call, and each <em>Strategy</em> 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 <em>Chain of
Responsibility</em>, a method calls itself, which (by moving down the chain of
<em>Strategies</em>) 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 <em>Strategies</em> is successful.</p>
<p>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
<strong>switch</strong> statement.</p>
<p>In the GoF, there&#8217;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&#8217;t matter how the chain is maintained; that&#8217;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
<em>Chain of Responsibility</em> 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&#8217;ll see that I&#8217;ve gone to some effort to
separate the chain-management parts of the implementation from the various
<em>Strategies</em>, so that the code can be more easily reused.</p>
<p>In <strong>StrategyPattern.py</strong>, above, what you probably want is to automatically
find a solution. <em>Chain of Responsibility</em> provides a way to do this by chaining
the <em>Strategy</em> objects together and providing a mechanism for them to
automatically recurse through each one in the chain:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># FunctionObjects/ChainOfResponsibility.py</span>

<span class="c"># Carry the information into the strategy:</span>
<span class="k">class</span> <span class="nc">Messenger</span><span class="p">:</span> <span class="k">pass</span>

<span class="c"># The Result object carries the result data and</span>
<span class="c"># whether the strategy was successful:</span>
<span class="k">class</span> <span class="nc">Result</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">succeeded</span> <span class="o">=</span> <span class="mf">0</span>
    <span class="k">def</span> <span class="nf">isSuccessful</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">succeeded</span>
    <span class="k">def</span> <span class="nf">setSuccessful</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">succeeded</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">succeeded</span> <span class="o">=</span> <span class="n">succeeded</span>

<span class="k">class</span> <span class="nc">Strategy</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="n">messenger</span><span class="p">):</span> <span class="k">pass</span>
    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="s">&quot;Trying &quot;</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">__class__</span><span class="o">.</span><span class="n">__name__</span> \
          <span class="o">+</span> <span class="s">&quot; algorithm&quot;</span>

<span class="c"># Manage the movement through the chain and</span>
<span class="c"># find a successful result:</span>
<span class="k">class</span> <span class="nc">ChainLink</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">chain</span><span class="p">,</span> <span class="n">strategy</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">strategy</span> <span class="o">=</span> <span class="n">strategy</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">chain</span> <span class="o">=</span> <span class="n">chain</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">chain</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">next</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c"># Where this link is in the chain:</span>
        <span class="n">location</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">chain</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">end</span><span class="p">():</span>
            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">chain</span><span class="p">[</span><span class="n">location</span> <span class="o">+</span> <span class="mf">1</span><span class="p">]</span>

    <span class="k">def</span> <span class="nf">end</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">chain</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">+</span> <span class="mf">1</span> <span class="o">&gt;=</span>
                <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">chain</span><span class="p">))</span>

    <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">messenger</span><span class="p">):</span>
        <span class="n">r</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">strategy</span><span class="p">(</span><span class="n">messenger</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">r</span><span class="o">.</span><span class="n">isSuccessful</span><span class="p">()</span> <span class="ow">or</span> <span class="bp">self</span><span class="o">.</span><span class="n">end</span><span class="p">():</span> <span class="k">return</span> <span class="n">r</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">next</span><span class="p">()(</span><span class="n">messenger</span><span class="p">)</span>

<span class="c"># For this example, the Messenger</span>
<span class="c"># and Result can be the same type:</span>
<span class="k">class</span> <span class="nc">LineData</span><span class="p">(</span><span class="n">Result</span><span class="p">,</span> <span class="n">Messenger</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">data</span> <span class="o">=</span> <span class="n">data</span>
    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="sb">`self.data`</span>

<span class="k">class</span> <span class="nc">LeastSquares</span><span class="p">(</span><span class="n">Strategy</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">messenger</span><span class="p">):</span>
        <span class="k">print</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="n">linedata</span> <span class="o">=</span> <span class="n">messenger</span>
        <span class="c"># [ Actual test/calculation here ]</span>
        <span class="n">result</span> <span class="o">=</span> <span class="n">LineData</span><span class="p">([</span><span class="mf">1.1</span><span class="p">,</span> <span class="mf">2.2</span><span class="p">])</span> <span class="c"># Dummy data</span>
        <span class="n">result</span><span class="o">.</span><span class="n">setSuccessful</span><span class="p">(</span><span class="mf">0</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">result</span>

<span class="k">class</span> <span class="nc">NewtonsMethod</span><span class="p">(</span><span class="n">Strategy</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">messenger</span><span class="p">):</span>
        <span class="k">print</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="n">linedata</span> <span class="o">=</span> <span class="n">messenger</span>
        <span class="c"># [ Actual test/calculation here ]</span>
        <span class="n">result</span> <span class="o">=</span> <span class="n">LineData</span><span class="p">([</span><span class="mf">3.3</span><span class="p">,</span> <span class="mf">4.4</span><span class="p">])</span> <span class="c"># Dummy data</span>
        <span class="n">result</span><span class="o">.</span><span class="n">setSuccessful</span><span class="p">(</span><span class="mf">0</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">result</span>

<span class="k">class</span> <span class="nc">Bisection</span><span class="p">(</span><span class="n">Strategy</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">messenger</span><span class="p">):</span>
        <span class="k">print</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="n">linedata</span> <span class="o">=</span> <span class="n">messenger</span>
        <span class="c"># [ Actual test/calculation here ]</span>
        <span class="n">result</span> <span class="o">=</span> <span class="n">LineData</span><span class="p">([</span><span class="mf">5.5</span><span class="p">,</span> <span class="mf">6.6</span><span class="p">])</span> <span class="c"># Dummy data</span>
        <span class="n">result</span><span class="o">.</span><span class="n">setSuccessful</span><span class="p">(</span><span class="mf">1</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">result</span>

<span class="k">class</span> <span class="nc">ConjugateGradient</span><span class="p">(</span><span class="n">Strategy</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">messenger</span><span class="p">):</span>
        <span class="k">print</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="n">linedata</span> <span class="o">=</span> <span class="n">messenger</span>
        <span class="c"># [ Actual test/calculation here ]</span>
        <span class="n">result</span> <span class="o">=</span> <span class="n">LineData</span><span class="p">([</span><span class="mf">7.7</span><span class="p">,</span> <span class="mf">8.8</span><span class="p">])</span> <span class="c"># Dummy data</span>
        <span class="n">result</span><span class="o">.</span><span class="n">setSuccessful</span><span class="p">(</span><span class="mf">1</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">result</span>

<span class="n">solutions</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">ChainLink</span><span class="p">(</span><span class="n">solutions</span><span class="p">,</span> <span class="n">LeastSquares</span><span class="p">()),</span>
<span class="n">ChainLink</span><span class="p">(</span><span class="n">solutions</span><span class="p">,</span> <span class="n">NewtonsMethod</span><span class="p">()),</span>
<span class="n">ChainLink</span><span class="p">(</span><span class="n">solutions</span><span class="p">,</span> <span class="n">Bisection</span><span class="p">()),</span>
<span class="n">ChainLink</span><span class="p">(</span><span class="n">solutions</span><span class="p">,</span> <span class="n">ConjugateGradient</span><span class="p">())</span>

<span class="n">line</span> <span class="o">=</span> <span class="n">LineData</span><span class="p">([</span>
  <span class="mf">1.0</span><span class="p">,</span> <span class="mf">2.0</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">,</span> <span class="mf">2.0</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.0</span><span class="p">,</span>
  <span class="mf">3.0</span><span class="p">,</span> <span class="mf">4.0</span><span class="p">,</span> <span class="mf">5.0</span><span class="p">,</span> <span class="mf">4.0</span>
<span class="p">])</span>

<span class="k">print</span><span class="p">(</span><span class="n">solutions</span><span class="p">[</span><span class="mf">0</span><span class="p">](</span><span class="n">line</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="section" id="exercises">
<h2>Exercises<a class="headerlink" href="#exercises" title="Permalink to this headline"></a></h2>
<ol class="arabic simple">
<li>Use <em>Command</em> in Chapter 3, Exercise 1.</li>
<li>Implement <em>Chain of Responsibility</em> to create an &#8220;expert system&#8221; 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
<strong>ProblemSolver</strong> object. What other pattern/patterns show up here?</li>
</ol>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id1" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label">[1]</td><td>In Python, all functions are already objects and so the <em>Command</em> pattern
is often redundant.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label">[2]</td><td><em>Design Patterns</em>, Page 235.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <p class="logo"><a href="index.html">
              <img class="logo" src="_static/cover.png" alt="Logo"/>
            </a></p>
    <font color="Red">This book is in early development; you will find parts that are incorrect &amp; incomplete.</font>
    
            <h3><a href="index.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="">Function Objects</a><ul>
<li><a class="reference external" href="#command-choosing-the-operation-at-runtime">Command: Choosing the Operation at Runtime</a></li>
<li><a class="reference external" href="#strategy-choosing-the-algorithm-at-runtime">Strategy: Choosing the Algorithm at Runtime</a></li>
<li><a class="reference external" href="#chain-of-responsibility">Chain of Responsibility</a></li>
<li><a class="reference external" href="#exercises">Exercises</a></li>
</ul>
</li>
</ul>


            <h4>Previous topic</h4>
            <p class="topless"><a href="Factory.html" title="previous chapter">Factory: Encapsulating Object Creation</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="ChangeInterface.html" title="next chapter">Changing the Interface</a></p>
            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="_sources/FunctionObjects.txt">Show Source</a></li>
            </ul>
    
          <h3>Quick search</h3>
            <form class="search" action="search.html" method="get">
              <input type="text" name="q" size="18" /> <input type="submit" value="Go" />
              <input type="hidden" name="check_keywords" value="yes" />
              <input type="hidden" name="area" value="default" />
            </form>
    <h4><a href="http://www.mindviewinc.com/Books/Python3Patterns/Index.php">Project Homepage</a></h4>
    <h4><a href="http://www.bitbucket.org/BruceEckel/python-3-patterns-idioms/issues/">Corrections/Suggestions</a></h4>
    <h4><a href="http://www.mindviewinc.com/Consulting/Index.php">Consulting &amp; Training</a></h4><br><br>

        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="ChangeInterface.html" title="Changing the Interface"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="Factory.html" title="Factory: Encapsulating Object Creation"
             accesskey="P">previous</a> |</li>
        <li><a href="index.html">Python 3 Patterns, Recipes and Idioms</a> &raquo;</li>
      </ul>
    </div>
    <div class="footer">
      &copy; Copyright 2008, Creative Commons Attribution-Share Alike 3.0.
      Last updated on Feb 13, 2009.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.5.
    </div>
  </body>
</html>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.