gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)
使用python实现单例模式
- User
使用python实现单例模式
- Assistant
Python实现单例模式可以使用装饰器或元类两种方式:
- 使用装饰器实现单例模式
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 MyClass: def __init__(self, name): self.name = name a = MyClass('a') b = MyClass('b') print(a.name) # a print(b.name) # a print(a is b) # True在这个例子中,我们使用装饰器
singleton来将原有的类转化为单例模式,返回一个新的函数get_instance来生成单例对象。- 使用元类实现单例模式
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): def __init__(self, name): self.name = name a = MyClass('a') b = MyClass('b') print(a.name) # a print(b.name) # a print(a is b) # True在这个例子中,我们定义了一个元类
Singleton,将原有的类转化为单例模式。在创建类的实例时,如果不存在该类实例,则创建实例,并将实例对象加入到Singleton.instances中,否则返回已存在的实例对象。 - User
使用python实现工厂设计模式
- Assistant
使用Python实现工厂设计模式有多种方式,下面介绍两种常见的实现方法:
- 简单工厂模式
class Car: def run(self): print("Car is running.") class Bus: def run(self): print("Bus is running.") class Factory: def create_vehicle(self, vehicle_type): if vehicle_type == 'car': return Car() elif vehicle_type == 'bus': return Bus() else: raise ValueError("Invalid vehicle type.") factory = Factory() vehicle1 = factory.create_vehicle('car') vehicle1.run() # Car is running. vehicle2 = factory.create_vehicle('bus') vehicle2.run() # Bus is running.在这个例子中,
Factory类是一个工厂类,在其中的create_vehicle方法中,根据vehicle_type参数决定创建哪种类型的交通工具。如果vehicle_type不是car或bus,则会抛出一个ValueError异常。- 工厂方法模式
from abc import ABC, abstractmethod class Vehicle(ABC): @abstractmethod def run(self): pass class Car(Vehicle): def run(self): print("Car is running.") class Bus(Vehicle): def run(self): print("Bus is running.") class VehicleFactory(ABC): @abstractmethod def create_vehicle(self): pass class CarFactory(VehicleFactory): def create_vehicle(self): return Car() class BusFactory(VehicleFactory): def create_vehicle(self): return Bus() car_factory = CarFactory() bus_factory = BusFactory() vehicle1 = car_factory.create_vehicle() vehicle1.run() # Car is running. vehicle2 = bus_factory.create_vehicle() vehicle2.run() # Bus is running.在这个例子中,将
Vehicle和VehicleFactory定义为抽象基类(ABC),并使用@abstractmethod装饰器定义抽象方法。Car和Bus类实现了Vehicle接口,CarFactory和BusFactory类实现了VehicleFactory接口。在create_vehicle方法中,分别返回Car和Bus类型的实例对象。这样增加新的交通工具类型时,只需要定义一个实现了Vehicle接口的类,并将其工厂实现为VehicleFactory的子类,即可通过工厂方法创建新的实例对象。