추상팩토리 패턴
예제
추상팩토리는(animal_factory)는 Class 또는 method 그 자체를 받는다.
그리고 추상팩토리를 정의한 클래스 내 메서드 안에서 추상팩토리를 사용한다.
import random
class PetShop:
def __init__(self, animal_factory=None):
self.pet_factory = animal_factory
def show_pet(self):
pet = self.pet_factory()
print("We have a lovely {}".format(pet))
print("It says {}".format(pet.speak()))
class Dog:
def speak(self):
return "woof"
def __str__(self):
return "Dog"
class Cat:
def speak(self):
return "meow"
def __str__(self):
return "Cat"
def random_animal():
return random.choice([Dog, Cat])()
def main():
shop = PetShop(random_animal)
shop.show_pet()
main()
예제
import enum
from abc import *
class Button:
@abstractmethod
def Paint(self):
pass
class WinButton(Button):
def Paint(self):
print ("Render a button in a Windows style")
class OSXButton(Button):
def Paint(self):
print ("Render a button in a Mac OSX style")
class MousePointer:
@abstractmethod
def Paint(self):
pass
class WinMousePointer(MousePointer):
def Paint(self):
print("Render a mousepointer in a Windows style")
class OSXMousePointer(MousePointer):
def Paint(self):
print ("Render a mousepointer in a OSX style")
class GUIFactory:
@abstractmethod
def CreateButton(self):
return Button
@abstractmethod
def CreateMousePointer(self):
return MousePointer
class WinFactory(GUIFactory):
def CreateButton(self):
return WinButton()
def CreateMousePointer(self):
return WinMousePointer()
class OSXFactory(GUIFactory):
def CreateButton(self):
return OSXButton()
def CreateMousePointer(self):
return OSXMousePointer()
class Settings:
@staticmethod
def Default():
return Appearance.WIN
class Appearance(enum.Enum):
WIN = 0
OSX = 1
def main():
apperance = Settings.Default()
if apperance == Appearance.WIN:
factory = WinFactory()
elif apperance == Appearance.OSX:
factory = OSXFactory()
button = factory.CreateButton()
mousePointer = factory.CreateMousePointer()
button.Paint()
mousePointer.Paint()
if __name__ == '__main__':
main()
'Design Pattern' 카테고리의 다른 글
데코레이터 패턴 (0) | 2023.07.25 |
---|---|
전략패턴 (0) | 2023.07.24 |
옵저버 패턴 (0) | 2023.07.24 |