처음부터 시작하는 개발자

[CS] 객체지향 프로그래밍 본문

CS

[CS] 객체지향 프로그래밍

hwcho0456 2023. 10. 15. 23:16

SOLID (객체지향 5원칙)

1. Single Responsibility Principle (단일 책임 원칙)

한 클래스는 하나의 책임만 가져야 한다.

 

class Order:
    def calculate_total_sum(self):
        pass
    def get_items(self):
        pass
    def print_order(self):
        pass  # SRP 위반: 주문 출력은 별도의 클래스에서 처리해야 합니다.

 

2. Open Closed Principle (개방 폐쇄 원칙)

“소프트웨어 요소는 확장에는 열려 있으나 변경에는 닫혀 있어야 한다.”

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

def draw_shapes(shapes):
    for shape in shapes:
        if isinstance(shape, Rectangle):  # OCP 위반: 새로운 도형이 추가될 때마다 메서드 수정 필요
            pass  # Draw rectangle...

 

 

3. Liskov Substitution Principle (리스코프 치환 원칙)

“프로그램의 객체는 프로그램의 정확성을 깨뜨리지 않으면서 하위 타입의 인스턴스로 바꿀 수 있어야 한다.”

class Bird:
    def fly(self):
        pass

class Ostrich(Bird):  # LSP 위반: 모든 새는 날 수 있는 것은 아닙니다.
    pass

bird = Bird()
ostrich = Ostrich()

bird.fly()  # Works fine...
ostrich.fly()  # Raises an error!

 

4. Interface Segregation Principle (인터페이스 분리 원칙)

“특정 클라이언트를 위한 인터페이스 여러 개가 범용 인터페이스 하나보다 낫다.”

class Worker:
    def work(self):
        pass
    def eat(self):
        pass

class Robot(Worker):  # ISP 위반: 로봇은 먹는 기능이 필요 없습니다.
    def work(self):
        pass
    def eat(self):
        raise NotImplementedError()

 

5. Dependency Inversion Principle (의존관계 역전 원칙)

프로그래머는 “추상화에 의존해야지, 구체화에 의존하면 안된다.”

from abc import ABC, abstractmethod

# 추상화 클래스
class Switchable(ABC):
    @abstractmethod
    def turn_on(self):
        pass
    
# 저수준 클래스 
class LightBulb(Switchable):  
    def turn_on(self):
        print("Light bulb turned on")

# 고수준 클래스 
class ElectricPowerSwitch:  
    def __init__(self, l: Switchable) -> None:
        self.light = l
        self.on = False

    def press(self) -> None:
        if self.on:
            self.light.turn_on()
            self.on = False
            print("Switch turned off")
            
        else:
            self.light.turn_on()
            self.on = True
            print("Switch turned on")

light_bulb = LightBulb()
switch = ElectricPowerSwitch(light_bulb)
switch.press()  # "Light bulb turned on" and "Switch turned on" will be printed.

'CS' 카테고리의 다른 글

[CS] HTTP의 개념  (0) 2023.12.10
[CS] AI를 위한 수학  (0) 2023.12.02
SQL for Data Analysis Cheat Sheet  (0) 2023.11.17
[CS] Apache Tomcat 개요  (0) 2023.11.09
[CS] Transformer 개요  (0) 2023.11.05