프롬프트 없음
개념 설명: 단일 책임 원칙은 클래스나 모듈이 한 가지의 책임만을 가져야 한다는 원칙입니다. 즉, 클래스는 하나의 기능이나 역할에만 집중해야 유지보수가 용이하고, 코드의 재사용성을 높일 수 있습니다.
class Game:
def start_game(self):
print("게임이 시작되었습니다.")
def save_game(self):
print("게임이 저장되었습니다.")
def load_game(self):
print("게임이 불러와졌습니다.")
class Game:
def start_game(self):
print("게임이 시작되었습니다.")
class GameManager:
def save_game(self):
print("게임이 저장되었습니다.")
def load_game(self):
print("게임이 불러와졌습니다.")
개념 설명: 개방-폐쇄 원칙은 소프트웨어의 엔티티(클래스, 모듈 등)는 확장에는 열려 있어야 하고, 수정에는 닫혀 있어야 한다는 원칙입니다. 즉, 기능을 추가할 때 기존 코드를 수정하지 않고도 새로운 기능을 추가할 수 있어야 합니다.
class Weapon:
def use(self):
print("무기를 사용합니다.")
class Player:
def __init__(self):
self.weapon = Weapon()
def attack(self):
self.weapon.use()
class Weapon:
def use(self):
raise NotImplementedError("이 메서드는 서브클래스에서 구현해야 합니다.")
class Sword(Weapon):
def use(self):
print("검으로 공격합니다.")
class Bow(Weapon):
def use(self):
print("활로 공격합니다.")
class Player:
def __init__(self, weapon):
self.weapon = weapon
def attack(self):
self.weapon.use()
리스코프 치환 원칙은 자식 클래스는 부모 클래스의 대체 가능해야 한다는 원칙입니다. 즉, 부모 클래스의 인스턴스를 자식 클래스의 인스턴스로 바꾸더라도 프로그램의 기능이 이상 없이 작동해야 합니다.
class Bird:
def fly(self):
print("새가 날아갑니다.")
class Ostrich(Bird):
def fly(self):
raise Exception("타조는 날 수 없습니다.")
class Bird:
def move(self):
print("새가 움직입니다.")
class Sparrow(Bird):
def move(self):
print("참새가 날아갑니다.")
class Ostrich(Bird):
def move(self):
print("타조가 달립니다.")
개념 설명: 인터페이스 분리 원칙은 클라이언트는 자신이 사용하지 않는 메서드에 의존하지 않아야 한다는 원칙입니다. 즉, 하나의 인터페이스가 여러 기능을 포함하기보다는 여러 개의 작은 인터페이스로 나누어야 합니다.
class MultiFunctionDevice:
def print(self):
print("인쇄 중...")
def scan(self):
print("스캔 중...")
def fax(self):
print("팩스 중...")
class Printer(MultiFunctionDevice):
def fax(self): # 필요하지 않은 메서드를 구현해야 함
raise NotImplementedError("팩스 기능이 없습니다.")
class Printer:
def print(self):
print("인쇄 중...")
class Scanner:
def scan(self):
print("스캔 중...")
class Fax:
def fax(self):
print("팩스 중...")
개념 설명: 의존성 역전 원칙은 고수준 모듈은 저수준 모듈에 의존해서는 안 되며, 두 모듈 모두 추상화에 의존해야 한다는 원칙입니다. 즉, 구체적인 클래스가 아닌 인터페이스나 추상 클래스에 의존해야 합니다.
class LightBulb:
def turn_on(self):
print("전구가 켜졌습니다.")
class Switch:
def __init__(self):
self.bulb = LightBulb()
def operate(self):
self.bulb.turn_on()
class Bulb:
def turn_on(self):
pass
class LightBulb(Bulb):
def turn_on(self):
print("전구가 켜졌습니다.")
class Switch:
def __init__(self, bulb: Bulb):
self.bulb = bulb
def operate(self):
self.bulb.turn_on()
# 사용 예
bulb = LightBulb()
switch = Switch(bulb)
switch.operate()
이 실습 자료는 모듈화의 기본 원칙을 이해하고 적용하는 데 도움을 주기 위해 구성되었습니다. 각 원칙을 이해하고, 예시 코드를 통해 실제로 적용해 보세요.