Adapting and strategizing
The adapter and strategy patterns are often thought of as separate patterns, but in Ruby, they are almost the same pattern, and the naming mostly depends on how the pattern is being applied. The adapter pattern is used for cases where you have one interface that you want to use, but you need to deal with various other objects that implement a different interface. With the adapter pattern, you write an adapter with the interface you want to use that wraps the objects that use a different interface. The strategy pattern is almost the same, except that instead of wrapping an object with a different interface, it implements a different approach for the same type of operation.
Let's say you want to implement a database library that needs to connect to multiple databases. You want the database library to use the execute
method for calling an SQL query on each database and getting results back. However, the driver for database M
uses the method exec
, the...