|
| 1 | +--- |
| 2 | +layout: recipe |
| 3 | +title: Bridge Pattern |
| 4 | +chapter: Design Patterns |
| 5 | +--- |
| 6 | + |
| 7 | +h2. Problem |
| 8 | + |
| 9 | +You need to maintain a reliable interface for code that can change frequently or change between multiple implementations. |
| 10 | + |
| 11 | +h2. Solution |
| 12 | + |
| 13 | +Use the Bridge pattern as an intermediate between the different implementations and the rest of the code. |
| 14 | + |
| 15 | +Assume that you developed an in-browser text editor that saves to the cloud. Now, however, you need to port it to a stand-alone client that saves locally. |
| 16 | + |
| 17 | +{% highlight coffeescript %} |
| 18 | +class TextSaver |
| 19 | + constructor: (@filename, @options) -> |
| 20 | + save: (data) -> |
| 21 | + |
| 22 | +class CloudSaver extends TextSaver |
| 23 | + constructor: (@filename, @options) -> |
| 24 | + super @filename, @options |
| 25 | + save: (data) -> |
| 26 | + # Assuming jQuery |
| 27 | + # Note the fat arrows |
| 28 | + $( => |
| 29 | + $.post "#{@options.url}/#{@filename}", data, => |
| 30 | + alert "Saved '#{data}' to #{@filename} at #{@options.url}." |
| 31 | + ) |
| 32 | + |
| 33 | +class FileSaver extends TextSaver |
| 34 | + constructor: (@filename, @options) -> |
| 35 | + super @filename, @options |
| 36 | + @fs = require 'fs' |
| 37 | + save: (data) -> |
| 38 | + @fs.writeFile @filename, data, (err) => # Note the fat arrow |
| 39 | + if err? then console.log err |
| 40 | + else console.log "Saved '#{data}' to #{@filename} in #{@options.directory}." |
| 41 | + |
| 42 | +filename = "temp.txt" |
| 43 | +data = "Example data" |
| 44 | + |
| 45 | +saver = if window? |
| 46 | + new CloudSaver filename, url: 'http://localhost' # => Saved "Example data" to temp.txt at http://localhost |
| 47 | +else if root? |
| 48 | + new FileSaver filename, directory: './' # => Saved "Example data" to temp.txt in ./ |
| 49 | + |
| 50 | +saver.save data |
| 51 | +{% endhighlight %} |
| 52 | + |
| 53 | +h2. Discussion |
| 54 | + |
| 55 | +The Bridge pattern helps you to move the implementation-specific code out of sight so that you can focus on your program's specific code. In the above example, the rest of your application can call _saver.save data_ without regard for where the file ultimately ends up. |
0 commit comments