|
| 1 | +--- |
| 2 | +layout: recipe |
| 3 | +title: Adapter patter |
| 4 | +chapter: Design patterns |
| 5 | +--- |
| 6 | +## Problem |
| 7 | + |
| 8 | +Suppose we have 3-rd party grid component. We want to apply there our own custom sorting but a small problem. Our custom sorter does not implement required interface by grid component. |
| 9 | +To understand the problem completely best example would be an socket from our usual life. Everybody knows this device. In some countries it has 3 pins and in other contries it has only 2 pins. |
| 10 | +This is exactly right situation to use [adapter pattern](https://en.wikipedia.org/wiki/Adapter_pattern). |
| 11 | + |
| 12 | +## Solution |
| 13 | + |
| 14 | +{% highlight coffeescript %} |
| 15 | +# a fragment of 3-rd party grid component |
| 16 | +class AwesomeGrid |
| 17 | + constructor: (@datasource)-> |
| 18 | + @sort_order = 'ASC' |
| 19 | + @sorter = new NullSorter # in this place we use NullObject pattern (another usefull pattern) |
| 20 | + setCustomSorter: (@customSorter) -> |
| 21 | + @sorter = customSorter |
| 22 | + sort: () -> |
| 23 | + @datasource = @sorter.sort @datasource, @sort_order |
| 24 | + # don't forget to change sort order |
| 25 | + |
| 26 | + |
| 27 | +class NullSorter |
| 28 | + sort: (data, order) -> # do nothing; it is just a stub |
| 29 | + |
| 30 | +class RandomSorter |
| 31 | + sort: (data)-> |
| 32 | + for i in [data.length-1..1] #let's shuffle the data a bit |
| 33 | + j = Math.floor Math.random() * (i + 1) |
| 34 | + [data[i], data[j]] = [data[j], data[i]] |
| 35 | + return data |
| 36 | + |
| 37 | +class RandomSorterAdapter |
| 38 | + constructor: (@sorter) -> |
| 39 | + sort: (data, order) -> |
| 40 | + @sorter.sort data |
| 41 | + |
| 42 | +agrid = new AwesomeGrid ['a','b','c','d','e','f'] |
| 43 | +agrid.setCustomSorter new RandomSorterAdapter(new RandomSorter) |
| 44 | +agrid.sort() # sort data with custom sorter through adapter |
| 45 | + |
| 46 | +{% endhighlight %} |
| 47 | + |
| 48 | +## Discussion |
| 49 | + |
| 50 | +Adapter is usefull when you have to organize an interaction between two objects with different interfaces. It can happen when you use 3-rd party libraries or you work with legacy code. |
| 51 | +In any case be carefull with adapter: it can be helpfull but it can instigate design errors. |
0 commit comments