Skip to content

Instantly share code, notes, and snippets.

@aliwo
Created March 29, 2022 13:40
Show Gist options
  • Save aliwo/bc14d02796a7f4321dad213a854ec5da to your computer and use it in GitHub Desktop.
Save aliwo/bc14d02796a7f4321dad213a854ec5da to your computer and use it in GitHub Desktop.
class QuackBehavior:
def quack(self):
pass
class SwimBehavior:
def swim(self):
pass
class NormalSwimBehavior(SwimBehavior):
def swim(self):
print("수영을 잘 하고 있습니다.")
class NoSwimBehavior(SwimBehavior):
def swim(self):
print("꼬르륵 가라앉습니다.")
class SwimWithPropeller(SwimBehavior):
def swim(self):
print("프로펠러 위이이잉")
class FlyBehavior:
def fly(self):
pass
class Duck:
def quack(self):
pass
def swim(self):
pass
def display(self):
pass
def fly(self):
print("훨훨 납니다.")
class MallardDuck(Duck):
def quack(self):
print('꽥꽥')
def swim(self):
print('어푸어푸')
def display(self):
print('청동오리모습')
class MallardDuck1(Duck):
def quack(self):
print('꽥꽥')
def swim(self):
print('어푸어푸')
def display(self):
print('청동오리모습')
class RubberDuck(Duck):
def quack(self):
print('삑삑')
def swim(self):
print('둥둥')
def display(self):
print('고무 장난감 오리입니다.')
def fly(self):
print("고무 오리는 날 수 없습니다.")
class WoodDuck(Duck):
swim_behavior = NoSwimBehavior() # type annotation
# def __init__(self, swim_behavior: SwimBehavior):
# self.swim_behavior = swim_behavior
def quack(self):
print('삑삑')
def swim(self):
self.swim_behavior.swim()
def display(self):
print('고무 장난감 오리입니다.')
def fly(self):
print("고무 오리는 날 수 없습니다.")
class CopperDuck(Duck):
swim_behavior: SwimBehavior
def __init__(self, swim_behavior: SwimBehavior):
self.swim_behavior = swim_behavior
def quack(self):
print('삑삑')
def swim(self):
self.swim_behavior.swim()
def display(self):
print('고무 장난감 오리입니다.')
def fly(self):
print("고무 오리는 날 수 없습니다.")
# wood_duck = WoodDuck(SwimWithPropeller())
# wood_duck = WoodDuck(NormalSwimBehavior())
print(WoodDuck.swim_behavior)
# 오늘 배운 것
# * 오버라이드
# * 원래 객체지향을 배울 떄에는 상태는 멤버변수에 담고, 행동은 메소드에 담는다고 배웠었습니다...만!
# * strategy 패턴에서는 behavior 를 담고있는 클래스를 만듭니다.
# * 그리고 이 class 를 상황에 맞게 "주입" 함으로써, Duck 클래스의 행동을 자유자재로 바꿀 수 있습니다.
# * "주입" -> injection
# 더 알아보면 좋을 것
# * ABC -> Abstract Base Class
# * Dependency Injection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment