doc.dev1x.org

Context Object

1. 目的

レイヤーをまたいだデータ共有の仕組み

2. 課題

レイヤー間で共有するデータを透過的に扱う必要がある

3. 解決策

レイヤー間で共有するデータを取りまとめたデータを定義する

class Context:
    """ Context Object """
    def __init__(self, id):
        self.id = id
        self.output = {}

def layer1(ctx):
    layer2(ctx)
    ctx.output["layer1"] = "Layer1 Completed."
    return ctx

def layer2(ctx):
    ctx.output["layer2"] = "Layer2 Completed."
    return ctx

def main():
    ctx = Context("ctx1")
    ctx = layer1(ctx)

    print(ctx.output["layer1"])   # => Layer1 Completed.
    print(ctx.output["layer2"])   # => Layer2 Completed.

4. メリット

シンプルな仕組みでレイヤー間のデータ共有が可能になる

5. デメリット

レイヤー間の結合度が上昇する

不要なデータまでレイヤー間で共有することになる

6. 注意

濫用は禁物

参考資料