Design pattern
객체지향 (디자인 패턴)
-
객체 지향 설계 패턴 : 객체 지향 프로그래밍 설계 경험을 통해 추천되는 설계 패턴을 구현한 것
-
싱글톤 패턴
클래스에 대한 객체가 한 개만 생성되도록 하는 패턴
객체를 생성할 때마다 메모리가 소모됨
객체 생성 시간, 메모리 사용량 등을 줄일 수 있음
class Singleton(type): __instances = {} def __call__(cls, *args, **kwargs): if cls not in cls.__instances: cls.__instances[cls] = super().__call__(cls, *args, **kwargs) return cls.__instances[cls]Singleton 클래스로 인스턴스를 생성한 적이 없다면 인스턴스를 생성 후 리턴
class PrintObject(metaclass=Singleton): def __init__(self): print("This is called by super().__call__") object1 = PrintObject() object2 = PrintObject() print(object1) print(object2)
-
옵저버 패턴
객체의 상태가 변했을 때 그 객체와 관련된 다른 객체들에게 상태가 변한 것을 알리는 패턴
class Observer: def __init__(self): self.observers = list() self.msg = str() def notify(self, event_data): for observer in self.observers: observer.notify(event_data) def register(self, observer): self.observers.append(observer) def unregister(self, observer): self.observers.remove(observer) class Notifier: def notify(self, event_data): print(event_data, "received") -
빌더 패턴
생성자에 들어갈 매개 변수가 너무 복잡해서 가독성이 떨어지고 어떤 변수가 어떤 값인지 알기 어렵거나 전체 변수 중 일부 값만 설정하는 경우
class Student(object): def __init__(self, name, age=20, height=180, weight=60, major="cs"): self.name = name self.age = age self.height = height self.weight = weight self.major = major student1 = Student("Dave") print(student1.name) print(student1.age) print(student1.height) print(student1.weight) print(student1.major)student1 = Student(major="ds", name="David") print(student1.name) print(student1.age) print(student1.height) print(student1.weight) print(student1.major) -
팩토리 패턴
객체를 생성하는 팩토리를 정의함
어떤 객체를 만들지는 팩토리 객체에서 결정함
class Androidsmartphone: def send(self, message): print("send a message via Android platform") class Iossmartphone: def send(self, message): print("send a message via IOS platform")class Smartphonefactory(object): def __init__(self): pass def create_smartphone(self,device_type) if device_type == "android": smartphone = AndroidSmartphone() elif device_type == "IOS": smartphone = IosSmartphone() return smartphonesmartphone_factory = Smartphonefactory() message_sender1 = smartphone_factory.create_smartphone("android") message_sender1.send("hello") message_sender1 = smartphone_factory.create_smartphone("IOS") message_sender1.send("hi")