在Python中实现设计模式通常是通过创建类和对象来实现的。以下是一些常见的设计模式以及在Python中实现的示例:
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
# 使用单例模式
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # True
class Shape:
def draw(self):
pass
class Circle(Shape):
def draw(self):
print("Drawing Circle")
class Rectangle(Shape):
def draw(self):
print("Drawing Rectangle")
class ShapeFactory:
def create_shape(self, shape_type):
if shape_type == "circle":
return Circle()
elif shape_type == "rectangle":
return Rectangle()
# 使用工厂模式
factory = ShapeFactory()
circle = factory.create_shape("circle")
circle.draw()
class Observer:
def update(self, message):
pass
class Subject:
def __init__(self):
self.observers = []
def add_observer(self, observer):
self.observers.append(observer)
def remove_observer(self, observer):
self.observers.remove(observer)
def notify_observers(self, message):
for observer in self.observers:
observer.update(message)
# 使用观察者模式
class ConcreteObserver(Observer):
def update(self, message):
print(f"Received message: {message}")
subject = Subject()
observer1 = ConcreteObserver()
observer2 = ConcreteObserver()
subject.add_observer(observer1)
subject.add_observer(observer2)
subject.notify_observers("Hello")
以上是一些常见的设计模式在Python中的实现示例,当然还有其他设计模式可以在Python中实现,具体实现方式取决于具体的设计模式和需求。