ファクトリーメソッド

Python 中級オブジェクト指向プログラミング

Jake Roach

Data Engineer

メソッド内の条件分岐

class Student:
    # 条件分岐だが、各条件で似た動作
    def explore_topic(self, resource_type, topic):
        if resource_type == "Textbook":
            print(f"Referencing {topic} using a textbook")
            self.reference_textbook(topic)

        elif resource_type == "Blog":
            print(f"Make sure to validate information provided in blogs!")
            self.reference_blog(topic)

        elif resource_type == "Video":
            self.reference_video(topic)
Python 中級オブジェクト指向プログラミング

ファクトリーメソッド

別メソッドで使うオブジェクトを、ファクトリーメソッドで生成するデザインパターン

  • インターフェースを実装するオブジェクトを返す
  • メソッドの複雑さを下げる
  • 再利用可能・モジュール化
  • ファクトリーメソッドには _ を付ける

$$

まずは製品と具体的な製品を見てみましょう。

...

  def _get_resource(self, resource_type):  
    if resource_type == "Textbook":
      # Textbook, Blog, Video は
      # すべて Resource
      return Textbook()  

    elif resource_type == "Blog":
      return Blog()  

    elif resource_type == "Video":
      return Video()
Python 中級オブジェクト指向プログラミング

Resource インターフェースを作る

class Resource(ABC):
    @abstractmethod
    def reference(self, topic):
        pass
class Textbook(Resource):
    def __init__(self):
        self.index = {"Object-oriented Programming": ["Inheritance", ...]}

    def reference(self, topic):
        print(f"Referencing {topic} using a textbook")
        return self.index.get(topic)

# Blog, Video も同様
Python 中級オブジェクト指向プログラミング

explore_topic() の書き換え

class Student:

    def explore_topic(self, resource_type, topic):
        if resource_type == "Textbook":
            texbook = Textbook()  # Resource を実装するクラスのインスタンスを生成
            texbook.reference(topic)  # reference() を呼ぶ

        elif resource_type == "Blog":
            blog = Blog()
            blog.reference(topic)

        elif resource_type == "Video":
            video = Video()
            video.reference(topic)
Python 中級オブジェクト指向プログラミング

ファクトリーメソッドを作る

class Student:
    # Resource を返すファクトリーメソッド
    def _get_resource(self, resource_type):
        if resource_type == "Textbook":
            return Textbook()  
        elif resource_type == "Blog":
            return Blog()  
        elif resource_type == "Video":
            return Video()

    def explore_topic(self, resource_type, topic):
        resource = self._get_resource(resource_type)  # リソースを取得
        return resource.reference(topic)
Python 中級オブジェクト指向プログラミング

ファクトリーメソッドを使う

# Student を作成し、教科書を参照する
lester = Student()
lester.explore_topic("Textbook", "Object-oriented Programming")

# その後、別のリソースに切り替え
lester.explore_topic("Video", "Object-oriented Programming")
Referencing Object-oriented Programming using a textbook
["Inheritance", "Constructors", "Class-level methods"]

Video are helpful for visual or audatory learners
["Classes", "Methods", "Attributes", "self"]
Python 中級オブジェクト指向プログラミング

練習してみましょう!

Python 中級オブジェクト指向プログラミング

Preparing Video For Download...