Structural Design Pattern
Structure Pattern의 시작
# Adaptee
class Banner():
def __init__(self, word):
self.word = word
def showWithParen(self):
print("(" + self.word + ")")
def showWithAster(self):
print("*" + self.word + "*")
# Target
class Print():
def printWeak(self):
pass
def printStrong(self):
pass
# Adapter
class PrintBanner(Banner, Print):
def __init__(self, word):
# 현재 클래스가 어떤 클래스인지 명확히 표기
# Super는 여기서 Banner가 Print보다 먼저 선언되었기 떄문에 Super는 Banner 뜻함
super(PrintBanner, self).__init__(word)
def printWeak(self):
self.showWithParen()
def printStrong(self):
self.showWithAster()
# Client
pb = PrintBanner("hello")
pb.printStrong() # *hello*
pb.printWeak() # (hello)
# Adaptee
class Banner():
def __init__(self, word):
self.word = word
def showWithParen(self):
print("(" + self.word + ")")
def showWithAster(self):
print("*" + self.word + "*")
# Target
class Print():
def printWeak(self):
pass
def printStrong(self):
pass
# Adapter
class PrintBanner(Print):
def __init__(self, word):
self.banner = Banner(word)
def printWeak(self):
self.banner.showWithParen()
def printStrong(self):
self.banner.showWithAster()
# Client
pb = PrintBanner("hello")
pb.printStrong() # *hello*
pb.printWeak() # (hello)
class Animal:
def walk(self):
pass
class Cat(Animal):
def walk(self):
print("cat walking")
class Dog(Animal):
def walk(self):
print("dog walking")
# client
def makeWalk(animal: Animal): # 다형성
animal.walk()
kitty = Cat()
bingo = Dog()
makeWalk(kitty) # cat walking
makeWalk(bingo) # dog walking
class Animal:
def walk(self):
pass
class Cat(Animal):
def walk(self):
print("cat walking")
class Dog(Animal):
def walk(self):
print("dog walking")
class Fish:
def swim(self):
print("fish swimming")
# client
def makeWalk(animal: Animal): # 다형성
animal.walk()
kitty = Cat()
bingo = Dog()
makeWalk(kitty) # cat walking
makeWalk(bingo) # dog walking
nemo = Fish()
makeWalk(nemo)
class Animal:
def walk(self):
pass
class Cat(Animal):
def walk(self):
print("cat walking")
class Dog(Animal):
def walk(self):
print("dog walking")
class Fish:
def swim(self):
print("fish swimming")
class FishAdapter(Animal):
def __init__(self, fish:Fish):
self.fish = fish
def walk(self):
self.fish.swim()
# client
def makeWalk(animal: Animal): # 다형성
animal.walk()
kitty = Cat()
bingo = Dog()
makeWalk(kitty) # cat walking
makeWalk(bingo) # dog walking
nemo = Fish()
adapted_nemo = FishAdapter(nemo)
makeWalk(adapted_nemo) # fish swimming
FishAdapter class는 Animal을 상속받고 constructor 안에서 Fish 객체를 받음