在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中實現,具體實現方式取決于具體的設計模式和需求。