python实现单例工厂模式

class CarFactory:

    '''python实现单例工厂模式'''

    __obj = None
    __flg_init = True

    def __new__(cls, *args, **kwargs):
        if cls.__obj is None:
            cls.__obj = object.__new__(CarFactory)

        return cls.__obj

    def __init__(self):
        if CarFactory.__flg_init:
            print('工厂产生了')
            CarFactory.__flg_init = False

    def creatCar(self, car_name):

        if car_name == 'Benz':
            car = Benz()

        elif car_name == 'BMW':
            car = BMW()

        else:
            car = BYD()

        return car


class Benz:
    def __init__(self):
        print('奔驰产生了')


class BMW:
    def __init__(self):
        print('宝马产生了')


class BYD:
    def __init__(self):
        print('比亚迪产生了')


cf = CarFactory()
cf2 = CarFactory()

print(cf)
print(cf2)

cf.creatCar('123')

cf2.creatCar('Benz')

相关推荐