Skip to content
The Chat Archive
gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)

使用python实现单例模式

  1. User

    使用python实现单例模式

  2. Assistant

    Python实现单例模式可以使用装饰器或元类两种方式:

    1. 使用装饰器实现单例模式
    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 来生成单例对象。

    1. 使用元类实现单例模式
    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 中,否则返回已存在的实例对象。

  3. User

    使用python实现工厂设计模式

  4. Assistant

    使用Python实现工厂设计模式有多种方式,下面介绍两种常见的实现方法:

    1. 简单工厂模式
    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 异常。

    1. 工厂方法模式
    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 的子类,即可通过工厂方法创建新的实例对象。