Python23.1_面向对象之解耦实例(简单工厂模式与工厂方法模式)

需求:设计4s店

class CarStore(object):
    def order(self, car_type):
        if car_type == "索拉塔":
            return Suonata()
        elif car_type == "名图":
            return Mingtu()
        elif car_type == "ix35":
            return Ix35()


class Car(object):
    def move(self):
        print("car is running...")

    def music(self, music_name):
        print("正在播放%s" % music_name)

    def stop(self):
        print("car has stoped")

class Suonata(Car):
    pass

class Mingtu(Car):
    pass

class Ix35(Car):
    pass

car_store = CarStore()
car = car_store.order("名图")
car.move()
car.music("绝世")
car.stop()

但是此种设计有一处缺陷,用户订购的车型一但发生改变,就需要对CarStore类的代码进行更新,而订购的车型应当是与汽车店关系并不太大的。因此,可以将车型的选择另用一个函数实现,用CarStore类中分离出来,实现解耦

class CarStore(object):
    def order(self, car_type):
        return select_car_by_type(car_type)
#将车型的选择从CarStore类中分离出来,实现解耦
def select_car_by_type(car_type):
    if car_type == "索拉塔":
        return Suonata()
    elif car_type == "名图":
        return Mingtu()
    elif car_type == "ix35":
        return Ix35
  • 改进:工厂设计模式

设计模式:解决某一类的问题可以按照某一种方法来进行。即解决某一种问题可以按照某一套路。

class CarStore(object):
    def __init__(self):
        self.factory = Factory()

    def order(self, car_type):
        return self.factory.select_car_by_type(car_type)

class Factory(object):  #Factory的作用,实现了解耦。CartStore需要一两车,就交给Facotryy这个类生产,这个类生产了再返回给CarStore
    #通过额外添加一个类来达到程序的解耦,称为简单工程模式
    def select_car_by_type(self,car_type):
        if car_type == "索拉塔":
            return Suonata()
        elif car_type == "名图":
            return Mingtu()
        elif car_type == "ix35":
            return Ix35()
  • 再改进:工厂方法模式

把一个方法定义在一个基类里面,不去实现这个功能,等到子类去继承这个类的时候,在子类里面再去把这个方法实现。在父类里面实现接口(方法),在子类里面实现方法的这种模式称为工厂方法模式

个人理解:即将做某件事情的流程,方法,专门用一个基类来实现,等到具体要做这件事情的时候,再让子类再重写部分方法。

class Store(object):
    def select_car(self):
        pass
    def order(self, car_type):
        return self.select_car()

class CarStore(Store):
    def order(self, car_type):
        return Factory().select_car_by_type(car_type)

class BMWStore(Store):
    def order(self, car_type):
        return Factory().select_car_by_type(car_type)

class Factory(Store):
    def select_car_by_type(self, car_type):
        if car_type == "索拉塔":
            return Suonata()
        elif car_type == "名图":
            return Mingtu()
        elif car_type == "ix35":
            return Ix35()
            
class Car(object):
    def move(self):
        print("car is running...")

    def music(self, music_name):
        print("正在播放%s" % music_name)

    def stop(self):
        print("car has stoped")

class Suonata(Car):
    pass

class Mingtu(Car):
    pass

class Ix35(Car):
    pass

car_store = CarStore()
car = car_store.order("名图")
car.move()
car.music("绝世")
car.stop()

猜你喜欢

转载自blog.csdn.net/qq_34873298/article/details/90646738