Python 中實現工廠模式
工廠模式是一種常見的設計模式,它可以幫助我們建立物件的過程更加靈活和可擴充套件。在 Python 中,我們可以使用函式和類來實現工廠模式。
工廠函式
下面是一個使用函式實現工廠模式的示例:
class Product:
def __init__(self, name):
self.name = name
def create_product(name):
return Product(name)
product = create_product("product_name")
在這個例子中,我們定義了一個Product
類,它有一個name
屬性。我們還定義了一個create_product
函式,它會建立一個Product
物件並返回它。我們可以透過呼叫create_product
函式來建立一個Product
物件。
工廠類
下面是一個使用類實現工廠模式的示例:
class Product:
def __init__(self, name):
self.name = name
class ProductFactory:
def create_product(self, name):
return Product(name)
factory = ProductFactory()
product = factory.create_product("product_name")
在這個例子中,我們定義了一個Product
類和一個ProductFactory
類。ProductFactory
類有一個create_product
方法,它會建立一個Product
物件並返回它。我們可以透過建立一個ProductFactory
物件並呼叫它的create_product
方法來建立一個Product
物件。
抽象工廠模式
抽象工廠模式是一種建立一組相關或相互依賴物件的介面,而無需指定它們的具體類的設計模式。在 Python 中,我們可以使用抽象基類來實現抽象工廠模式。
下面是一個使用抽象基類實現抽象工廠模式的示例:
from abc import ABC, abstractmethod
class Product(ABC):
@abstractmethod
def do_something(self):
pass
class ProductA(Product):
def do_something(self):
print("ProductA is doing something.")
class ProductB(Product):
def do_something(self):
print("ProductB is doing something.")
class Factory(ABC):
@abstractmethod
def create_product(self):
pass
class FactoryA(Factory):
def create_product(self):
return ProductA()
class FactoryB(Factory):
def create_product(self):
return ProductB()
factory_a = FactoryA()
product_a = factory_a.create_product()
product_a.do_something()
factory_b = FactoryB()
product_b = factory_b.create_product()
product_b.do_something()
在這個例子中,我們定義了一個Product
抽象基類和兩個具體的Product
類。每個具體的Product
類都實現了do_something
方法。我們還定義了一個Factory
抽象基類和兩個具體的Factory
類。每個具體的Factory
類都實現了create_product
方法,它會建立一個具體的Product
物件並返回它。我們可以透過建立一個具體的Factory
物件並呼叫它的create_product
方法來建立一個具體的Product
物件。
單例模式
單例模式是一種保證一個類只有一個例項,並提供一個訪問它的全域性訪問點的設計模式。在 Python 中,我們可以使用元類來實現單例模式。
下面是一個使用元類實現單例模式的示例:
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class MyClass(metaclass=Singleton):
pass
instance_1 = MyClass()
instance_2 = MyClass()
print(instance_1 is instance_2)
在這個例子中,我們定義了一個Singleton
元類,它會保證一個類只有一個例項。我們還定義了一個MyClass
類,它使用Singleton
元類來實現單例模式。我們可以透過建立兩個MyClass
物件並比較它們是否相同來驗證單例模式的實現。
更多內容可以學習《測試工程師 Python 工具開發實戰》書籍、《大話效能測試 JMeter 實戰》書籍