Python編程高手通常熟練運(yùn)用各種設(shè)計(jì)模式,這些設(shè)計(jì)模式有助于提高代碼的可維護(hù)性、可擴(kuò)展性和重用性。
以下是一些Python編程高手常用的設(shè)計(jì)模式:
1.單例模式(Singleton Pattern)
確保一個類只有一個實(shí)例,并提供全局訪問點(diǎn)。適用于需要共享資源或控制特定資源訪問的情景。
class Singleton(object):
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
s1 = Singleton()
s2 = Singleton()
print(id(s1))
print(id(s2)) # s1和s2的ID應(yīng)該是一樣的,表明這是同一個對象
其他實(shí)現(xiàn)單例模式的方法。
1.1?使用模塊級別的變量實(shí)現(xiàn)單例模式
# singleton_module.py
class Singleton:
def __init__(self):
self.value = None
def set_value(self, value):
self.value = value
def get_value(self):
return self.value
singleton_instance = Singleton()
Python模塊在程序中只會被導(dǎo)入一次,因此模塊級別的變量可以實(shí)現(xiàn)單例模式。
在其他文件中,可以通過導(dǎo)入singleton_module
模塊來獲取單例對象:
# main.py
from singleton_module import singleton_instance
# 使用單例對象
singleton_instance.set_value(42)
print(singleton_instance.get_value())
1.2 使用類裝飾器實(shí)現(xiàn)單例模式
可以使用裝飾器來確保類只有一個實(shí)例,并通過裝飾器在需要時創(chuàng)建實(shí)例。
# singleton_decorator.py
def singleton(cls):
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class Singleton:
def __init__(self):
self.value = None
def set_value(self, value):
self.value = value
def get_value(self):
return self.value
在這種方式下,可以直接使用@singleton
裝飾器標(biāo)記一個類為單例,然后通過類的實(shí)例獲取單例對象:
# main.py
from singleton_decorator import Singleton
# 使用單例對象
singleton_instance = Singleton()
singleton_instance.set_value(42)
print(singleton_instance.get_value())
2. 工廠模式(Factory Pattern)
-
?定義一個接口,但由子類決定實(shí)例化哪個類。工廠方法模式將類的實(shí)例化延遲到子類。
class Product(ABC): @abstractmethod def create_product(self): pass class ConcreteProductA(Product): def create_product(self): return "Product A" class ConcreteProductB(Product): def create_product(self): return "Product B"
3.觀察者模式(Observer Pattern)
from abc import ABC, abstractmethod
class Observer(ABC):
@abstractmethod
def update(self, message):
pass
class ConcreteObserver(Observer):
def update(self, message):
print(f"Received message: {message}")
class Subject:
_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)
??????4. 策略模式(Strategy Pattern)
-
定義一系列算法,將每個算法封裝起來,并使它們可以互換。策略模式可以使算法獨(dú)立于客戶端而變化。文章來源:http://www.zghlxwxcb.cn/news/detail-820082.html
from abc import ABC, abstractmethod class Strategy(ABC): @abstractmethod def execute(self): pass class ConcreteStrategyA(Strategy): def execute(self): return "Strategy A" class ConcreteStrategyB(Strategy): def execute(self): return "Strategy B" class Context: def __init__(self, strategy): self._strategy = strategy def execute_strategy(self): return self._strategy.execute()
5.裝飾器模式(Decorator Pattern)
-
?動態(tài)地給一個對象添加一些額外的職責(zé),裝飾模式比繼承更加靈活。文章來源地址http://www.zghlxwxcb.cn/news/detail-820082.html
from abc import ABC, abstractmethod class Component(ABC): @abstractmethod def operation(self): pass class ConcreteComponent(Component): def operation(self): return "Concrete Component" class Decorator(Component): _component = None def __init__(self, component): self._component = component def operation(self): return self._component.operation() class ConcreteDecorator(Decorator): def operation(self): return f"{super().operation()}, Decorated"
到了這里,關(guān)于【Python進(jìn)階編程】python編程高手常用的設(shè)計(jì)模式(持續(xù)更新中)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!