做社区生意的网站,官网建设报价,建网站 广州,游戏网页代码目录
一、工厂模式#xff08;Factory Pattern#xff09; 二、单例模式#xff08;Singleton Pattern#xff09;
三、观察者模式#xff08;Observer Pattern#xff09; 一、工厂模式#xff08;Factory Pattern#xff09; 工厂模式#xff08;Factory Pattern…目录
一、工厂模式Factory Pattern 二、单例模式Singleton Pattern
三、观察者模式Observer Pattern 一、工厂模式Factory Pattern 工厂模式Factory Pattern工厂模式是一种创建型模式它提供了一种创建对象的最佳方式。在工厂模式中我们在创建对象时不会对客户端暴露创建逻辑并且是通过使用一个共同的接口来指向新创建的对象。
Python 例子
class Creator:def factory_method(self):raise NotImplementedError(Subclasses must implement this method!)class ConcreteProductA(Creator):def factory_method(self):return ProductA()class ConcreteProductB(Creator):def factory_method(self):return ProductB()class ProductA:passclass ProductB:passdef client_code(creator):product creator.factory_method()product.do_something()# 使用
creator_a ConcreteProductA()
client_code(creator_a)creator_b ConcreteProductB()
client_code(creator_b) 二、单例模式Singleton Pattern 单例模式Singleton Pattern单例模式是一种创建型模式它确保一个类只有一个实例并提供一个全局访问点。
Python 例子
class Singleton:_instance Nonedef __new__(cls):if cls._instance is None:cls._instance super().__new__(cls)return cls._instancesingleton_instance Singleton()
another_instance Singleton()# singleton_instance 和 another_instance 是同一个实例
print(singleton_instance is another_instance) # 输出: True三、观察者模式Observer Pattern 观察者模式Observer Pattern观察者模式是一种行为型模式它定义了一种一对多的依赖关系让多个观察者对象同时监听某一个主题对象当主题对象状态发生改变时它的所有依赖者观察者都会收到通知并自动更新。
Python 例子
class Subject:def __init__(self):self._observers []def attach(self, observer):self._observers.append(observer)def notify(self):for observer in self._observers:observer.update()class Observer:def update(self):raise NotImplementedError(Subclasses must implement this method!)class ConcreteObserver(Observer):def update(self):print(Observer received an update!)# 使用
subject Subject()
observer ConcreteObserver()
subject.attach(observer)
subject.notify() # 输出: Observer received an update! 代码之美在于创造无限可能