読み書きプログラミング

日常のプログラミングで気づいたことを綴っています

インスタンス変数にメソッドを委譲する

継承は使いたくないけど、インスタンス変数のメソッドをサポートしたい場合、同じ名前のメソッドを定義してそのインスタンス変数に委譲することになります。

関数delegateは、委譲するクラス、委譲されるクラス、そのインスタンス変数名を与えると、委譲するクラスに委譲メソッドを追加します。

delegate = (delegateClass, instanceVariableClass, instanceVariableName) ->
    for name, method of instanceVariableClass.prototype when typeof method is 'function'
        delegateClass.prototype[name] = ((instanceVariableName, name) ->
            () ->
                array = []
                array.push.apply array, arguments
                @[instanceVariableName][name].apply @[instanceVariableName], array
        )(instanceVariableName, name)

# execution example

class Instance
  # definitions
  # ...
  sampleMethod: (n) -> console.log n

class Example
    constructor: () ->
        @instance = new Instance()

delegate Example, Instance, 'instance'
a = new Example()
a.sampleMethod 0