Introduction to the Adapter Pattern Using Ruby

Introduction to the Adapter Pattern

In our journey through Structural Patterns, we’ve examined how they help manage object compositions and relationships, aiding in more scalable and flexible systems. The Adapter Pattern is no different; it focuses on enabling two incompatible interfaces to work together seamlessly.

Imagine you have a European plug that you need to use with a U.S. socket. They are inherently incompatible, but through an adapter, you can bridge this gap. Similarly, in software design, you often encounter situations where you need to integrate classes with incompatible interfaces. The Adapter Pattern provides a way to achieve this integration.

What You'll Learn

In this lesson, you'll learn how to implement the Adapter Pattern using Ruby. We'll start with a simple example where we have a European plug that needs to connect to a U.S. socket.

Here's a snippet from the code you'll be working with:

The following snippet defines a EuropeanPlug class with an engage method:

class EuropeanPlug
  def engage
    puts "European plug connected."
  end
end

Next, we have a USPlug interface, which we will simulate using a module, indicating the intended interface for the client:

module USPlug
  def connect
    raise NotImplementedError, "This is an interface method"
  end
end

Finally, we have an Adapter class that adapts the EuropeanPlug to the USPlug interface:

class Adapter
  include USPlug
  
  def initialize(plug)
    @plug = plug
  end

  def connect
    @plug.engage
  end
end

Here is how we'd interact with the classes:

european_plug = EuropeanPlug.new
adapter = Adapter.new(european_plug)

adapter.connect # Output: European plug connected.

In this example, EuropeanPlug has a method engage that we want to adapt to the USPlug interface. The Adapter class bridges the gap between the two interfaces by implementing the USPlug interface and delegating the call to the EuropeanPlug object.

Key Components of the Adapter Pattern

Let's understand the key components of the Adapter Pattern:

  • Target Interface: The expected interface used by the client (in our example, USPlug).
  • Adaptee: The existing interface that needs adapting (in our example, EuropeanPlug).
  • Adapter: The class that bridges the gap between the Target Interface and Adaptee.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal