LoginSignup
0

More than 5 years have passed since last update.

PythonでFactoyMethod

Last updated at Posted at 2018-04-16

FactoryMethodが便利だったのでメモ。FactoryMethodはデザインパターンの一つで、一般的なインスタンス生成とは異なる方法でインスタンスを生成できます。具体的にはstrを渡してインスタンスが生成できるので、いろいろ使える場面がある気がする。

使い方の例

class Dog:
    def bark(self):
        print('ワンワン')

class Cat:
    def bark(self):
        print('ニャーニャー')

def pet_shop(pet):
    # これがFactoryMethod
    pets = dict(Dog=Dog, Cat=Cat)
    return pets[pet]()

my_dog = pet_shop('Dog')
my_dog.bark()
# >> ワンワン
my_cat = pet_shop('Cat')
my_cat.bark()
# >> ニャーニャー

参考ページ
python-patterns

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