建造者模式和抽象工厂模式对比

建造者模式python代码:
按照建造者模式设计一个生产车辆是按照一个设计蓝图,需要把车辆进行拆分,拆分为引擎和车轮两部分,然后由建造者进行建造,他注重的是对零件的装配、组合、封装,类图如下(实习地方不让上传图片,具体的类图可以参考《设计模式之禅》第395页类图

class ICar(object):
    """基类"""
    def Engine(self):
        # 不同类型的产品,该步骤的细节可能不同
        raise NotImplementedError()

    def Wheel(self):
        # 不同类型的产品,该步骤的细节可能不同
        raise NotImplementedError()

class BenzBuilder(ICar):
    """派生类,生产builder1类型的产品"""
    def Engine(self):
        print('BenzBuilder Engine')

    def Wheel(self):
        print('BenzBuilder Wheel')

class BMWBuilder(ICar):
    """派生类,生产builder2类型的产品"""
    def Engine(self):
        print('BMWBuilder Engine')

    def Wheel(self):
        print('BMWBuilder Wheel')

class Director(object):
    """指挥者,负责组织产品的构建过程"""
    def Build(self, builder):
        builder.Engine()
        builder.Wheel()

def client():
    director = Director()
    director.Build(BenzBuilder())
    director.Build(BMWBuilder())
if __name__=='__main__':
    client()

抽象工厂模式不会关心构建过程,只关心什么产品由什么工厂生产即可。具体代码如下:

class car:
    '''interface as Product'''
    def drive(self):
        pass

class BMW(car):
    '''Concrete Product'''
    def __init__(self,carname):
        self.__name=carname
    def drive(self):
        print("Drive the BMW as "+self.__name)

class Benz(car):
    '''Concrete Product'''
    def __init__(self,carname):
        self.__name=carname
    def drive(self):
        print("Drive the Benz as "+self.__name)

class driver:
    '''Factory also called Creator'''
    def driverCar(self):
        return car()

class BMWdriver(driver):
    '''Concrete Creator'''
    def driverCar(self):
        return BMW("BMW")

class Benzdriver(driver):
    '''Concrete Creator'''
    def driverCar(self):
        return Benz("Benz")    

if __name__ == "__main__":
    driver=BMWdriver()
    car=driver.driverCar()
    car.drive()
    driver=Benzdriver()
    car=driver.driverCar()
    car.drive()

你可能感兴趣的:(设计模式,python)