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!")
以上是三种常见设计模式的实现方式,你可以根据需要选择合适的设计模式来实现你的程序。