返回
化繁为简:设计模式的简单示例
前端
2023-11-25 23:10:01
设计模式在软件开发中扮演着举足轻重的角色,帮助我们构建灵活、可重用和易于维护的代码。它们是经过验证的最佳实践集合,为解决常见问题提供了优雅而高效的解决方案。为了让设计模式的概念更易理解,让我们来看看一些常用的设计模式及其简单示例。
单例模式
单例模式确保一个类只有一个实例,无论该类被创建了多少次。它常用于创建全局对象,例如数据库连接或配置管理器。
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
工厂模式
工厂模式负责创建对象,而无需指定其确切的类型。这使我们能够在不改变客户端代码的情况下轻松更改创建的类。
class ShapeFactory:
def create_shape(self, shape_type):
if shape_type == "circle":
return Circle()
elif shape_type == "square":
return Square()
else:
raise ValueError("Invalid shape type")
策略模式
策略模式允许我们在运行时改变算法或行为。它通过将算法封装在单独的类中来实现,使我们可以轻松地交换不同的策略。
class Strategy:
def algorithm(self, data):
pass
class ConcreteStrategyA(Strategy):
def algorithm(self, data):
# Implement algorithm A
pass
class ConcreteStrategyB(Strategy):
def algorithm(self, data):
# Implement algorithm B
pass
观察者模式
观察者模式允许一个对象(称为主题)通知多个对象(称为观察者)有关其状态的任何更改。它通常用于实现松散耦合的事件处理。
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def detach(self, observer):
self._observers.remove(observer)
def notify(self):
for observer in self._observers:
observer.update(self)
class Observer:
def update(self, subject):
# Handle update from subject
pass