Adapter Pattern - CoffeeScript Design Patterns

By on

The Adapter Pattern can make you a hero. How? Well imagine this scenario: you’ve written some awesome code. It does exactly what it needs to do, and it does a damn good job of it. Everyone is happy.

Time goes by and you find yourself working on a project that has remarkably similar functionality. You think to yourself, “I could reuse that awesome code from before and literally cut my development time in half!” Problem is, they don’t share the same interface.

In other words: new-project is looking for something different than awesome-code is exposing. Here’s how you fix that, save a shit-ton of time, and a probably get more chest hair. (Sorry if you’re a girl. Chest hair can be unseemly, but we’re all geeks here and will totally accept you and your marginally hairy chest.)

[code lang=“coffee”]

Defines the domain-specific interface that Client uses.

class Target
request: () ->
console.log "Not fired"

  1. Defines an existing interface that needs adapting.

class Adaptee
specificRequest: () ->
console.log "Specific request"

  1. Adapts the interface of Adaptee to the Target interface.

class Adapter extends Target
constructor: (@adaptee) ->
request: () ->


[code lang=“coffee”]

Collaborates with objects conforming to the Target interface.

class Client
@run: () ->
adaptee = new Adaptee()
adapter = new Adapter adaptee