![Adapter](/images/patterns/cards/adapter-mini.png?id=b2ee4f681fb589be5a0685b94692aebb)
Adapter en Ruby
Adapter es un patrón de diseño estructural que permite colaborar a objetos incompatibles.
El patrón Adapter actúa como envoltorio entre dos objetos. Atrapa las llamadas a un objeto y las transforma a un formato y una interfaz reconocible para el segundo objeto.
Complejidad:
Popularidad:
Ejemplos de uso: El patrón Adapter es muy común en el código Ruby. Se utiliza muy a menudo en sistemas basados en algún código heredado. En estos casos, los adaptadores crean código heredado con clases modernas.
Identificación: Adapter es reconocible por un constructor que toma una instancia de distinto tipo de clase abstracta/interfaz. Cuando el adaptador recibe una llamada a uno de sus métodos, convierte los parámetros al formato adecuado y después dirige la llamada a uno o varios métodos del objeto envuelto.
Ejemplo conceptual
Este ejemplo ilustra la estructura del patrón de diseño Adapter. Se centra en responder las siguientes preguntas:
- ¿De qué clases se compone?
- ¿Qué papeles juegan esas clases?
- ¿De qué forma se relacionan los elementos del patrón?
main.rb: Ejemplo conceptual
# The Target defines the domain-specific interface used by the client code.
class Target
# @return [String]
def request
'Target: The default target\'s behavior.'
end
end
# The Adaptee contains some useful behavior, but its interface is incompatible
# with the existing client code. The Adaptee needs some adaptation before the
# client code can use it.
class Adaptee
# @return [String]
def specific_request
'.eetpadA eht fo roivaheb laicepS'
end
end
# The Adapter makes the Adaptee's interface compatible with the Target's
# interface.
class Adapter < Target
# @param [Adaptee] adaptee
def initialize(adaptee)
@adaptee = adaptee
end
def request
"Adapter: (TRANSLATED) #{@adaptee.specific_request.reverse!}"
end
end
# The client code supports all classes that follow the Target interface.
def client_code(target)
print target.request
end
puts 'Client: I can work just fine with the Target objects:'
target = Target.new
client_code(target)
puts "\n\n"
adaptee = Adaptee.new
puts 'Client: The Adaptee class has a weird interface. See, I don\'t understand it:'
puts "Adaptee: #{adaptee.specific_request}"
puts "\n"
puts 'Client: But I can work with it via the Adapter:'
adapter = Adapter.new(adaptee)
client_code(adapter)
output.txt: Resultado de la ejecución
Client: I can work just fine with the Target objects:
Target: The default target's behavior.
Client: The Adaptee class has a weird interface. See, I don't understand it:
Adaptee: .eetpadA eht fo roivaheb laicepS
Client: But I can work with it via the Adapter:
Adapter: (TRANSLATED) Special behavior of the Adaptee.