资讯详情

python设计模式

📅 2026/9/12 14:12:02 | 华诺云谱 👁 阅读
python设计模式
一、实例模式以下是一个简单的单例模式示例class Singleton: _instance None def __new__(cls): if cls._instance is None: cls._instance super().__new__(cls) return cls._instance a Singleton() b Singleton() print(a is b) # 输出True二、工厂模式以下是一个简单的工厂模式示例class Dog: def speak(self): return 汪汪 class Cat: def speak(self): return 喵喵 def create_animal(animal_type): if animal_type dog: return Dog() elif animal_type cat: return Cat() animal create_animal(dog) print(animal.speak()) # 输出汪汪三、外观模式以下是一个简单的外观模式示例class CPU: def start(self): print(CPU 启动) class Memory: def load(self): print(内存加载) class Computer: def init(self): self.cpu CPU() self.memory Memory() def boot(self): self.cpu.start() self.memory.load() computer Computer() computer.boot() 输出 CPU 启动 内存加载四、适配器模式以下是一个简单的适配器模式示例class ChineseSocket: def provide(self): return 220V 交流电 class USPlug: def connect(self, socket): return socket.provide() class Adapter: def __init__(self, socket): self.socket socket def provide(self): return self.socket.provide() socket ChineseSocket() adapter Adapter(socket) plug USPlug() print(plug.connect(adapter)) # 输出220V 交流电五、观察者模式以下是一个简单的观察者模式示例class Subject: def __init__(self): self.observers [] def attach(self, observer): self.observers.append(observer) def notify(self, message): for observer in self.observers: observer.update(message) class Observer: def update(self, message): print(f收到消息{message}) subject Subject() obs Observer() subject.attach(obs) subject.notify(你好) 输出收到消息你好六.状态模式
📝

华诺云谱内容团队

资深建站顾问 · 行业研究员

10年+企业数字化服务经验,专注智能建站、SEO优化与品牌营销,持续输出建站技巧、行业洞察与营销干货,已帮助5000+企业实现数字化增长。

你可能需要的服务

订阅华诺云谱资讯周报

每周一封,精选建站技巧、SEO与营销干货,直达邮箱。已有 8,000+ 企业主订阅,助你少走弯路。