Skip to content

Commit 5774755

Browse files
committed
Create adapter
1 parent 28e5392 commit 5774755

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Diff for: chapters/design_patterns/adapter

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
---
2+
layout: default
3+
title: Adapter pattern
4+
---
5+
6+
## Sample recipe template
7+
8+
Create a new `my-recipe.md` file and use this text as a start.
9+
10+
{% highlight text %}
11+
---
12+
layout: recipe
13+
title: Adapter patter
14+
chapter: Design patterns
15+
---
16+
## Problem
17+
18+
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.
19+
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.
20+
This is exactly right situation to use adapter.
21+
22+
## Solution
23+
24+
#grid component
25+
class AwesomeGrid
26+
constructor: (@datasource)->
27+
@sort_order = 'ASC'
28+
@sorter = new NullSorter # in this place we use NullObject pattern (another usefull pattern)
29+
setCustomSorter: (@customSorter) ->
30+
@sorter = customSorter
31+
sort: () ->
32+
@datasource = @sorter.sort @datasource, @sort_order
33+
# don't forget to change sort order
34+
35+
36+
class NullSorter
37+
sort: (data, order) -> # do nothing; it is just a stub
38+
39+
class RandomSorter
40+
sort: (data)->
41+
for i in [data.length-1..1] #let's shuffle the data a bit
42+
j = Math.floor Math.random() * (i + 1)
43+
[data[i], data[j]] = [data[j], data[i]]
44+
return data
45+
46+
class RandomSorterAdapter
47+
constructor: (@sorter) ->
48+
sort: (data, order) ->
49+
@sorter.sort data
50+
51+
agrid = new AwesomeGrid ['a','b','c','d','e','f']
52+
agrid.setCustomSorter new RandomSorterAdapter(new RandomSorter)
53+
agrid.sort() # sort data with custom sorter through adapter
54+
55+
## Discussion
56+
57+
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.
58+
In any case be carefull with adapter: it can be helpfull but it can instigate design errors.
59+
60+
{% endhighlight %}

0 commit comments

Comments
 (0)