OOP에서 팩토리란 다른 클래스의 객체를 생성하는 클래스를 말한다.
일반적으로 팩토리는 객체와 관련 메소드로 구성돼 있다. 클라이언트는 특정 인자와 함께 메소드를 호출하고 팩토리는 해당 객체를 생성하고 반환한다.
인터페이스는 객체 생성 로직을 숨기고 객체를 생성한다.
from abc import ABCMeta, abstractmethod
class Animal(metaclass=ABCMeta):
@abstractmethod
def do_say(selfself):
pass
class Dog(Animal):
def do_say(self):
print("Bhow Bhow!!!")
class Cat(Animal):
def do_say(self):
print("meow Meow!!!")
class ForestFactory(object):
def make_sound(selfself, object_type):
return eval(object_type)().do_say()
if __name__ == '__main__':
ff = ForestFactory()
animal = input("Dog or Cat")
ff.make_sound(animal)
from abc import ABCMeta, abstractmethod
#
# 아래는 Product 인터페이스
#
class Section(metaclass=ABCMeta):
@abstractmethod
def describe(self):
pass
class PersonalSection(Section):
def describe(self):
print("Persnonal Section")
class PatentSection(Section):
def describe(self):
print("PatentSection")
# Creator 추상 클래스
class Profile(metaclass=ABCMeta):
def __init__(self):
self.sections = []
self.createProfile()
@abstractmethod
def createProfile(self):
pass
def getSetions(self):
return self.sections
def addSections(self, section):
self.sections.append(section)
# ConcreateCreator 클래스
class Linkedin(Profile):
def createProfile(self):
self.addSections(PersonalSection())
self.addSections(PatentSection())
class Facebook(Profile):
def createProfile(self):
self.addSections(PersonalSection())
if __name__ == '__main__':
profile_type = input('Linkedin or Facebook')
profile = eval(profile_type)()
print('Creating Profile..', type(profile).__name__)
print('Profile has sections --', profile.getSetions())