2006-08-09

Java vs. Ruby: Adapters

Here's Java to adapt an OpenCloseDevice to an OnOffDevice:
// OnOffAdapter.java
public class OnOffAdapter implements OnOffDevice {
  private OpenCloseDevice myDevice;
  public OnOffAdapter(OpenCloseDevice adaptedDevice) {
    myDevice = adaptedDevice;
  }
  public void on() {
    myDevice.close();
  }
  public void off() {
    myDevice.open();
  }
}
// OnOffAdapter usage
OnOffDevice valveAdapter = new OnOffAdapter(reliefValve);

Ruby equivalent:
valve_adapter = Adapter.new(relief_valve,
  :on  => :close,
  :off => :open)

Reference: Thinking in Ruby