k-tokitoh

2019-05-13

Rubyによるデザインパターン - proxy

[![Rubyによるデザインパターン](https://images-fe.ssl-images- amazon.com/images/I/41PNvUxHtgL.SL160.jpg)](http://www.amazon.co.jp/exec/obidos/ASIN/4894712857/hatena- blog-22/)

利用する場面

あるオブジェクトに関してアクセス制御などを行うとき、本体とは異なる代理のオブジェクトにその責務を引き受けさせる。

サンプル

class Locker
  def initialize
    @items = []
  end

  def check(item)
    @items << item
  end

  def pickup(item)
    @items.delete(item)
  end
end

class LockerProxy
  def initialize(locker, password)
    @locker = locker
    @password = password
  end

  def check(item)
    @locker.check(item)
  end

  def pickup(item)
    while true do
      case gets.chomp
      when "exit"
        return
      when @password
        return @locker.pickup(item)
      else
        p "wrong password"
        next
      end
    end
  end
end


> my_locker = LockerProxy.new(Locker.new, "1234")
> my_locker.check(:baggage)
> my_locker.pickup(:baggage)
2345 # => "wrong password"
1234 # => :baggage

proxy に限らないが、全面的に委譲したいときには method_missing をつかうといい。 例えば上記の LockerProxy#check などの単なる(インターフェースが全く変わらない)委譲メソッドを書く代わりに、以下のようにすれば 1 つのメソッドでことが済む。

def method_missing(name, *args)
  @locker.send(name, *args)
end

その他