モデル設計---抽象工場モデル
抽象ファクトリモード(Abstract Factory)は、作成型ファクトリモードの1つです.
特徴:お客様は抽象クラスで定義されたインタフェースとのみ対話し、特定のクラスのインタフェースを使用しません.
ここではpythonの例です.実行環境はpython 2.7です.
ここでは主に抽象工場について簡単な学習を行う.
ここでは主にget_を通してファクトリの選択を行うにはfactory関数を使用します.同時に、各リアルオブジェクトがファクトリクラスに対応して構築されます.
新しいオブジェクトごとにファクトリクラスを再定義すると、抽象ファクトリを使用してクラスの数が増加し、エンジニアリングの構築中のクラスの数に一定のトラブルが発生します.
特徴:お客様は抽象クラスで定義されたインタフェースとのみ対話し、特定のクラスのインタフェースを使用しません.
ここではpythonの例です.実行環境はpython 2.7です.
import random
class PetShop:
"""A pet shop"""
def __init__(self, animal_factory=None):
self.pet_factory = animal_factory
def show_pet(self):
"""Create and show a pet using the abstract factory"""
pet = self.pet_factory.get_pet()
print("This is a lovely", pet)
print("It says", pet.speak())
print("It eats", self.pet_factory.get_food())
class Dog:
def speak(self):
return "woof"
def __str__(self):
return "Dog"
class Cat:
def speak(self):
return "meow"
def __str__(self):
return "Cat"
# Factory classes
class DogFactory:
def get_pet(self):
return Dog()
def get_food(self):
return "dog food"
class CatFactory:
def get_pet(self):
return Cat()
def get_food(self):
return "cat food"
def get_factory():
"""Let's be dynamic!"""
return random.choice([DogFactory, CatFactory])()
if __name__ == "__main__":
factory = PetShop(get_factory())
for i in range(3):
factory.show_pet()
print("="*20)
ここでは主に抽象工場について簡単な学習を行う.
ここでは主にget_を通してファクトリの選択を行うにはfactory関数を使用します.同時に、各リアルオブジェクトがファクトリクラスに対応して構築されます.
新しいオブジェクトごとにファクトリクラスを再定義すると、抽象ファクトリを使用してクラスの数が増加し、エンジニアリングの構築中のクラスの数に一定のトラブルが発生します.