From 3ed1c5d0e4018fc70012a6209a859a059f7127b5 Mon Sep 17 00:00:00 2001 From: zhang Date: Fri, 25 Mar 2022 00:11:34 +0800 Subject: =?UTF-8?q?=E6=9B=B4=E6=96=B0=E8=84=9A=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- oop/dp/Decorator.py | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 oop/dp/Decorator.py (limited to 'oop/dp/Decorator.py') diff --git a/oop/dp/Decorator.py b/oop/dp/Decorator.py new file mode 100644 index 0000000..390935a --- /dev/null +++ b/oop/dp/Decorator.py @@ -0,0 +1,59 @@ + +from abc import ABCMeta, abstractmethod + + +class Person(metaclass=ABCMeta): + def __init__(self, name): + self._name = name + + @abstractmethod + def wear(self): + print('着装: ') + + +class Engineer(Person): + + def __init__(self, name, skill): + super().__init__(name) + self._skill = skill + + def wear(self): + print(f'我是 {self._name} 工程师, 我会 {self._skill}') + super().wear() + + +class ClothingDecorator(Person): + def __init__(self, person: Person): + self._decoratored = person + + def wear(self): + self._decoratored.wear() + self.decorate() + + @abstractmethod + def decorate(self): + pass + + +class CasualPantDecorator(ClothingDecorator): + def __init__(self, person: Person): + super().__init__(person) + def decorate(self): + print('一条卡其色裤子') + + +class BeltDecorator(ClothingDecorator): + def __init__(self, person: Person): + super().__init__(person) + + def decorate(self): + print('一条黑色腰带') + +if __name__ == '__main__': + tony = Engineer('Tony', '算法') + pant = CasualPantDecorator(tony) + belt = BeltDecorator(pant) + belt.wear() + + + -- cgit v1.2.3