LoginSignup
1
2

More than 1 year has passed since last update.

駆け出しpythonエンジニアのまとめ デザインパターンまとめ6(adapter)

Posted at

趣旨

駆け出しエンジニアの備忘録の垂れ流し。
 ※ 出典漏れがあればご指摘ください

出典:
https://yamakatsusan.web.fc2.com/
https://dackdive.hateblo.jp/
https://www.oreilly.co.jp/books/9784873117393/

adapterパターン概要

オブジェクトの構成に関するデザインパターンの1つ。
既存クラスのインターフェイスにラッパーを実装し、別のクラスと互換性をもたせる。
主な実装方法として、継承を利用する方法と移譲を利用する方法がある。

Adapter パターンの目的は,“既存の”オブジェクトのインタフェースを変換することである。

クラス図とシーケンス図

68747470733a2f2f71696974612d696d6167652d73746f72652e73332e61702d6e6f727468656173742d312e616d617a6f6e6177732e636f6d2f302f3130333539352f37653635343537612d626236622d376366662d353236352d3965626663346434653230652e6a706567.jpeg

wikipediaより引用

実装方針

継承を利用する場合

  • 利用したいクラス(Adaptee)を継承したAdapterクラスを作る。
  • Adapterクラスにはclient向けのIFを実装し、メソッド内で、スーパクラスのIFを利用する処理を書く。
実装例1

class Adaptee:
   def specific_operation(some_args):
      hogehoge()

class Adapter(Adaptee):

   @classmethod
   def create(cls: Adapter):
        return cls()

   def wrapper_operation(self):
       some_args = make_args()
       self.specfic_operation(some_args)

# client側
def main():
    adpt = Adapter.cerate()
    adpt.wrapper_operation()

移譲を利用する場合

実装例2

class Adaptee:
   def specific_operation(some_args):
      hogehoge()

class Adapter:
   def __init__(self, adaptee_cls: Adaptee):
      self._adaptee = adaptee_csl

  @classmethod
   def create(cls):
      return cls(Adaptee())

   def wrapper_operation(self):
       some_args = make_args()
       self._adaptee.specfic_operation(some_args)

# client側
def main():
    adpt = Adapter.cerate()
    adpt.wrapper_operation()

使い所

  • 使い所
    • 既存のクラスのインタフェースが、必要なインタフェースと一致していないケース
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2