1.应用场景:流程审批,顺序链式处理,控制每个子模块执行处理的次数,控制子模块执行顺序。

2.应用: 通过对一个全链条中的全局变量,全局实例进行赋值修改变量,达到控制子模块是否执行,执行次数,决定下一个是否执行的作用。

class Car:
    def __init__(self):
        self.name=None
        self.km=11000
        self.fuel=5
        self.oil=5

def handle_fuel(car):
    if car.fuel<10:
        print('add fuel')
        car.fuel=100
def handle_km(car):
    if car.km>10000:
        print('made a car test')
        car.km=0
def handle_oil(car):
    if car.oil<10:
        print('add oil')
        car.oil=100

class Garage:
    def __init__(self):
        self.handles=[]
    def add_handler(self,handler):
        self.handles.append(handle)
    def handle_car(self,car):
        for handle in self.handles:
            handle(car)

if __name__ == '__main__':

    handlers = [handle_fuel, handle_km, handle_oil]

    garage = Garage()



    for handle in handlers:

        garage.add_handler(handle)

    garage.handle_car(Car())



龙仔
12 声望4 粉丝