Strategy-like Pattern in PHP
Today, I had some time to write a little program while I was watching people work on the infrastructure at the office. I wrote up a couple of functions that calculated the n-th Fibonacci number, and wanted to display the sequence of the first 100 numbers as they were calculated by these functions. At first, I had something like the following:
<?php
for( $i = 1; $i < = 100; ++$i ) { printf( "%d ", fibonacci_tabularized( $i ) ); } for( $i = 1; $i < = 100; ++$i ) { printf( "%d, ", fibonacci_iterative( $i ) ); } for( $i = 1; $i < = 100; ++$i ) { printf( "%d, ", fibonacci_recursive( $i ) ); }
?>
I quickly realized how horrible it was. That sure is a lot of duplicate code! So, I ended up rewriting it so that it looks like this:
<?php
function print_fibonacci_sequence( $strategy, $n ) { for( $i = 1; $i < = $n; ++$i ) { printf( "%d, ", $strategy($n) ); } printf( "\r\n" ); } $strategies = array( "fibonacci_tabularized", "fibonacci_iterative", "fibonacci_recursive" ); foreach( $strategies as $strategy ) { print_fibonacci_sequence( $strategy, 100 ); }
?>