파이썬 데코레이터
Americano, Soy 2.49
결과는 위의 결과처럼 Americano 에 Soy가 추가되서 가격은 1.99 + 0.5 = 2.49 가 되었다.
Decorator Pattern in Python
데코레이터 패턴이란?? [링크]
데코레이터 패턴(Decorator pattern)이란 주어진 상황 및 용도에 따라 어떤 객체에 책임을 덧붙이는 패턴으로, 기능 확장이 필요할 때 서브클래싱 대신 쓸 수 있는 유연한 대안이 될 수 있다. [위키피디아]
간단하게 말해서 객체에 없던 기능을 추가하여 객체를 꾸며주는 것이다.
# Python 에서 추상 클래스와 메소드를 만들기 위해 추가 from abc import ABCMeta, abstractmethod # 음료 클래스 class Beverage(object): __metaclass__ = ABCMeta #추상 클래스로 선언 def __init__(self): self.description = "Null" def get_description(self): return self.description @abstractmethod #추상 메소드 선언 def cost(self): pass # 음료를 상속받은 아메리카노 객체 선언 class Americano(Beverage): #아메리카노 객체 생성 def __init__(self): self.description = "Americano" #가격을 리컨하는 함수 def cost(self): return 1.99 # 데코레이터 클래스 선언 class CondimentDecorator(Beverage): __metaclass__ = ABCMeta @abstractmethod def get_description(self): pass # 소이밀크를 추가하는 클래스 선언 - 데코레이터 상속 class Soy(CondimentDecorator): def __init__(self, beverage): self.beverage = beverage #기존 음료에 소이밀크 추가 def get_description(self): return self.beverage.get_description() + ", Soy" #기존 음료수 가격에 소이밀크 가격 추가 def cost(self): return self.beverage.cost() + 0.5 a = Americano() a_soy = Soy(a) print a_soy.get_description(), a_soy.cost()
커피를 몰라서 아메리카노에 소이밀크를 추가해봤습니다.
오류 및 질문에 대한 댓글 환영합니다.