Python設計模式是通過編寫符合特定設計模式規范的代碼來實現的。以下是一些常見設計模式的實現方式:
class Singleton:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
# 使用單例模式創建實例
instance1 = Singleton()
instance2 = Singleton()
print(instance1 is instance2) # True
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class AnimalFactory:
def create_animal(self, animal_type):
if animal_type == "dog":
return Dog()
elif animal_type == "cat":
return Cat()
# 使用工廠模式創建實例
factory = AnimalFactory()
dog = factory.create_animal("dog")
cat = factory.create_animal("cat")
print(dog.speak()) # "Woof!"
print(cat.speak()) # "Meow!"
from abc import ABC, abstractmethod
from typing import List
class Observer(ABC):
@abstractmethod
def update(self, message: str):
pass
class Subject:
_observers: List[Observer] = []
def add_observer(self, observer: Observer):
self._observers.append(observer)
def remove_observer(self, observer: Observer):
self._observers.remove(observer)
def notify_observers(self, message: str):
for observer in self._observers:
observer.update(message)
# 使用觀察者模式
class ConcreteObserver(Observer):
def update(self, message: str):
print(f"Received message: {message}")
subject = Subject()
observer1 = ConcreteObserver()
observer2 = ConcreteObserver()
subject.add_observer(observer1)
subject.add_observer(observer2)
subject.notify_observers("Hello, world!")
以上是三種常見設計模式的實現方式,你可以根據需要選擇合適的設計模式來實現你的程序。