개방-폐쇄 원칙(OCP, Open-Closed Principle)은 '소프트웨어 개체(클래스, 모듈, 함수 등등)는 확장에 대해 열려 있어야 하고, 수정에 대해서는 닫혀 있어야 한다'는 프로그래밍 원칙이다. -> https://ko.wikipedia.org/wiki/%EA%B0%9C%EB%B0%A9-%ED%8F%90%EC%87%84_%EC%9B%90%EC%B9%99
개방-폐쇄 원칙 - 위키백과, 우리 모두의 백과사전
개방-폐쇄 원칙(OCP, Open-Closed Principle)은 '소프트웨어 개체(클래스, 모듈, 함수 등등)는 확장에 대해 열려 있어야 하고, 수정에 대해서는 닫혀 있어야 한다'는 프로그래밍 원칙이다. 상세설명[편집]
ko.wikipedia.org
class Animal():
def __init__(self,type):
self.type = type
def hey(animal):
if animal.type == 'Cat':
print('meow')
elif animal.type == 'Dog':
print('bark')
bingo = Animal('Dog')
kitty = Animal('Cat')
#Cow와 Sheep을 추가하기위해 hey함수의 수정이 필요하다.
hey(bingo)
hey(kitty)
이런 문제를 해결하기위해 extends, abstracts를 사용
class Animal:
def speak(self): #interface method
pass
class Cat(Animal):
def speak(self):
print("meow")
class Dog(Animal):
def speak(self):
print("bark")
class Sheep(Animal):
def speak(self):
print("meh")
class Cow(Animal):
def speak(self):
print("moo")
def hey(animal):
animal.speak();
bingo = Dog()
kitty = Cat()
sheep = Sheep()
cow = Cow()
hey(bingo)
hey(kitty)
hey(sheep)
hey(cow)
즉, Animal을 interface로 사용하여 확장성 갖고 있는 디자인 패턴
'Dev. > 객체지향' 카테고리의 다른 글
| Dependency Inversion principle(의존성 주입 원칙) (0) | 2022.03.29 |
|---|---|
| Interface segregation principle(인터페이스 분리 원칙) (0) | 2022.03.29 |
| Liskov Substitution principle(리스코프 치환 원칙) (0) | 2022.03.29 |
| Single Responsibility(단일 책임 원칙) (0) | 2022.03.29 |