팩토리 패턴

런던행·2020년 8월 4일
0

디자인 패턴

목록 보기
3/8

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())

추상 팩토리 패턴

profile
unit test, tdd, bdd, laravel, django, android native, vuejs, react, embedded linux, typescript

0개의 댓글