Share This Article
The proxy pattern is a software design pattern that provides a surrogate object that controls access to another object.
A proxy can be used to control access to an object, delay the creation of an object, or act as a placeholder for another object.
In ruby, you can implement the proxy pattern using the Forwardable module, which is part of the standard library.
Let’s see an example:
require "forwardable"
class User
def initialize(name)
@name = name
end
def greet
"hello, #{@name}"
end
end
class UserProxy
extend Forwardable
def_delegators :@user, :greet
def initialize(user)
@user = user
end
end
user = User.new("jane")
user_proxy = UserProxy.new(user)
puts user_proxy.greet
# hello, jane
Let’s break down this code.
First, we create a User class with a greet method.
Then we create a UserProxy class that uses the forwardable module to delegate the greet method to the User instance.
Finally, we create an instance of the User class and an instance of the UserProxy class.
When we call the greet method on the UserProxy instance, it delegates the call to the User instance and we get the expected result.
The Proxy Pattern vs The Adapter Pattern
In ruby, the adapter pattern is also commonly used to provide a surrogate object.
What’s the difference between the two patterns?
The adapter pattern is typically used when you want to adapt an existing object to a new interface. in other words, it’s used to convert the interface of an object to a different interface.
On the other hand, the proxy pattern is typically used to control access to an object. it can also be used to delay an object’s creation or act as a placeholder for another object.
Summary
You’ve learned how to implement the proxy pattern in ruby in this article using the forwardable module.
You’ve also learned about the difference between the proxy pattern & the adapter pattern.
Finally, you’ve seen how the proxy pattern can be used to control access to an object, delay the creation of an object, or act as a placeholder for another object.