0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pythonで書くBuilderパターン

Last updated at Posted at 2023-01-17

概要

  • コンストラクタに対して数多くのパラメータをセットする必要がある時に、代わりに使うことが推奨されている実装方法
  • メジャーな実装方法
    • GoF
    • Effective Java
  • Javaで書かれることが多いので今回はPythonを用いて実装

Builderパターンなし

#!/usr/bin/env python3
# -*- coding: utf_8 -*-
"""builderパターンなし
"""

class People:
    def __init__(self, name, sex, age):
        self._name = name
        self._sex = sex
        self._age = age

    def __repr__(self):
        return f"People(name = {self._name}, sex = {self._sex}, age = {self._age})"


if __name__ == "__main__":
    people = People("taku ikegami", "", 26)
    print(repr(people))

GoFのBuilderパターン

#!/usr/bin/env python3
# -*- coding: utf_8 -*-
"""GoFのBuilderパターン
"""

import abc


class Builder(metaclass=abc.ABCMeta):
    """「表現形式」を決定する抽象クラス"""

    @abc.abstractmethod
    def add_name(self, name):
        raise NotImplementedError()

    @abc.abstractmethod
    def add_sex(self, sex):
        raise NotImplementedError()

    @abc.abstractmethod
    def add_age(self, age):
        raise NotImplementedError()

    @abc.abstractmethod
    def get_result(self):
        raise NotImplementedError()


class PeopleBuilder(Builder):
    """「表現形式」を決定するクラス"""

    def __init__(self):
        self._people = People()

    def add_name(self, name):
        self._people.name = name

    def add_sex(self, sex):
        self._people.sex = sex

    def add_age(self, age):
        self._people.age = age

    def get_result(self):
        return self._people


class Director:
    """「作成過程」を決定するクラス"""

    def __init__(self, builder: Builder):
        self._builder = builder

    def construct(self):
        self._builder.add_name("taku ikegami")
        self._builder.add_sex("")
        self._builder.add_age(26)
        return self._builder.get_result()


class People:
    name: str
    sex: str
    age: int

    def __repr__(self):
        return f"People(name = {self.name}, sex = {self.sex}, age = {self.age})"


if __name__ == "__main__":
    builder = PeopleBuilder()
    director = Director(builder)
    people = director.construct()
    print(repr(people))

Effective JavaのBuilderパターン

#!/usr/bin/env python3
# -*- coding: utf_8 -*-
"""Effective JavaのBuilderパターン
"""


class People:
    def __init__(self, builder):
        self._name = builder._name
        self._sex = builder._sex
        self._age = builder._age

    class Builder:
        def __init__(self, name):
            self._name = name
            self._sex = None
            self._age = None

        def add_sex(self, sex):
            self._sex = sex
            return self

        def add_age(self, age):
            self._age = age
            return self

        def build(self):
            return People(self)

    def __repr__(self):
        return f"People(name = {self._name}, sex = {self._sex}, age = {self._age})"


if __name__ == "__main__":
    people = People.Builder("taku ikegami").add_age(26).add_sex("").build()
    print(repr(people))

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?