Delegation is a design pattern and a concept in software engineering where an object handles a request by passing it to a second “delegate” object. The delegate object is responsible for performing the actual task. This pattern is used to achieve separation of concerns and to promote code reuse and flexibility.
Key Points
- Separation of Concerns: Delegation helps in separating the responsibilities of different objects, making the code more modular and easier to maintain.
- Code Reuse: By delegating tasks to other objects, you can reuse existing code and avoid duplication.
- Flexibility Delegation allows you to change the behavior of an object at runtime by changing its delegate.
Example in Ruby
In Ruby, delegation can be achieved using the Forwardable
module or the delegate method.
Using Forwardable
Module
require 'forwardable'
class Printer
def print_message(message)
puts message
end
end
class Document
extend Forwardable
def_delegators :@printer, :print_message
def initialize
@printer = Printer.new
end
end
doc = Document.new
doc.print_message("Hello, World!") # Output: Hello, World!
Using delegate Method
require 'delegate'
class Printer
def print_message(message)
puts message
end
end
class Document < SimpleDelegator
def initialize
super(Printer.new)
end
end
doc = Document.new
doc.print_message("Hello, World!") # Output: Hello, World!
doc = Document.new
Summary
Delegation is a design pattern that allows an object to pass a request to a delegate object to handle the actual task. It promotes separation of concerns, code reuse, and flexibility in software design.