May 09, 2021 CoffeeScript
Imagine traveling abroad, and once you realize that your power cord socket is not compatible with the outlet on the wall of your hotel room, luckily you remember to bring your power adapter. It connects one side to your power cord socket and the other to the wall outlet, allowing communication between them.
The same situation can occur in code when two (or more) instances (classes, modules, etc.) want to communicate with each other, but their communication protocols (for example, the language they use communicate in) are different. I n this case, adapter mode is more convenient. It acts as a translator, from side to side.
# a fragment of 3-rd party grid component
class AwesomeGrid
constructor: (@datasource)->
@sort_order = 'ASC'
@sorter = new NullSorter # in this place we use NullObject pattern (another useful pattern)
setCustomSorter: (@customSorter) ->
@sorter = customSorter
sort: () ->
@datasource = @sorter.sort @datasource, @sort_order
# don't forget to change sort order
class NullSorter
sort: (data, order) -> # do nothing; it is just a stub
class RandomSorter
sort: (data)->
for i in [data.length-1..1] #let's shuffle the data a bit
j = Math.floor Math.random() * (i + 1)
[data[i], data[j]] = [data[j], data[i]]
return data
class RandomSorterAdapter
constructor: (@sorter) ->
sort: (data, order) ->
@sorter.sort data
agrid = new AwesomeGrid ['a','b','c','d','e','f']
agrid.setCustomSorter new RandomSorterAdapter(new RandomSorter)
agrid.sort() # sort data with custom sorter through adapter
Adapters are useful when you want to organize interactions between two objects with different interfaces. I t can be used when you use a third-party library or use legacy code. Use the adapter carefully in any case: it can be useful, but it can also cause design errors.