PDH 개발 공부

open Closed principles, 개방 폐쇄 원칙 본문

Design Pattern/SOLID

open Closed principles, 개방 폐쇄 원칙

IFBB 2021. 11. 9. 17:38

Open closed principle을 준수하지 않는 Animal

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)

// 결과

bark
meow

상속을 이용한 Animal class. 추가되는 동물에 대해 hey함수의 수정을 필요로 하지 않는다

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)

// 결과

bark
meow
meh
moo

python/javascript같은 언어에서는 Open closed principle을 위해 꼭 상속 개념을 필요로 하지는 않음. (Animal class가 없어도 됨)


class Cat():
  def speak(self):
    print("meow")

class Dog():
  def speak(self):
    print("bark")

def hey(animal):
  animal.speak();

bingo = Dog()
kitty = Cat()

hey(bingo)
hey(kitty)

// 결과
bark
meow
  • 즉 Animal를 인터페이스를 두고 고양이 , 개 , 양 , 소 에 대해서 확장에 열려 있고. 수정에 대해는 닫혀 있는 구조
Comments