Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Strategyパターン

Sponsored · SiteGround - Reliable hosting with speed, security, and support you can count on.

 Strategyパターン

Avatar for Hank Ehly

Hank Ehly

June 29, 2022
Tweet

More Decks by Hank Ehly

Other Decks in Technology

Transcript

  1. 概要 • コンテキスト(Context)に Strategy を渡す • コンポジション • コンテキストが Strategy

    に処理を委託する class Context: def __init__(self, strategy): self.strategy = strategy def operation(self): self.strategy.operation()
  2. 概要 • Strategy は、ランタイムで選択できる if url.startswith("s3://"): context = Context(strategy=S3()) elif

    url.startswith("gs://"): context = Context(strategy=GoogleCloudStorage()) else: context = Context(strategy=LocalStorage()) • Contextの中身を修正せずに振る舞いを変えている • Contextを「拡張」している ◦ テスト修正 / デグレ確認が減る
  3. いつ使うか 1. 関連しているアルゴリズムの「やること」が同じで「やり方」だけ違う Random Forest と Deep Learning 2. ディスク容量、実行時間、ネットワーク速度などの考慮

    ネットワークが遅い時は、画像の画質を多少落として送信する 3. メソッドの振る舞いを if/else で分岐して実装している時 いくつかの「Strategy」に分ける
  4. class Storage: def upload(self, data, path): pass class S3(Storage): def

    upload(self, data, path): print("S3の {path} に {data} をアップロードする ") class Context: def __init__(self, storage: Storage): self.storage = storage def upload(self, data, path): self.storage.upload(data, path) context = Context(storage=S3()) context.upload(b"hello world", "s3://bucket/file.csv") コード例
  5. class Storage: def upload(self, data, path): pass class S3(Storage): def

    upload(self, data, path): print("S3の {path} に {data} をアップロードする ") class Context: def __init__(self, storage: Storage): self.storage = storage def upload(self, data, path): self.storage.upload(data, path) context = Context(storage=S3()) context.upload(b"hello world", "s3://bucket/file.csv") コード例
  6. class Storage: def upload(self, data, path): pass class S3(Storage): def

    upload(self, data, path): print("S3の {path} に {data} をアップロードする ") class Context: def __init__(self, storage: Storage): self.storage = storage def upload(self, data, path): self.storage.upload(data, path) context = Context(storage=S3()) context.upload(b"hello world", "s3://bucket/file.csv") コード例
  7. コード例 class Storage: def upload(self, data, path): pass class S3(Storage):

    def upload(self, data, path): print("S3の {path} に {data} をアップロードする") class Context: def __init__(self, storage: Storage): self.storage = storage def upload(self, data, path): self.storage.upload(data, path) context = Context(storage=S3()) context.upload(b"hello world", "s3://bucket/file.csv")