python 设计模式(二) 六大设计原则一 单一职责原则(SRP)

单一职责原则(single responsibility principle)

        简称SRP。There should never be more than one reason for a class to change.仅有一种原因引起类的改变。一个类只负责一个职责。

单一职责原则 这地址讲的很好,但不是用python语言实现的,在这里我用python语言实现一下。

问题由来:类A负责职责1和职责2,在正常运行中没有出现任何问题,但当职责1改变时,需要修改类A,可能引起正常运行的职责2发生问题

解决方案:遵循单一职责原则,分别创建类A和类B来负责职责1和职责2。这样设计当修改其一,并不会影响其二工作

在工程实践中,随着项目修改的变更或者其他原因,经常会出现职责扩散,比如类A原本负责职责1,但由于需求的变更,职责1被细分为职责11和职责12,导致类A无法正常工作

实例代码python实现

class Animal(object):
    def __init__(self):
        pass

    def breathe(self, name):
        print('%s 呼吸空气' %name)


# caller
class Client(object):
    def __init__(self):
        pass

    def work(self):
        animal = Animal()
        animal.breathe('牛')
        animal.breathe('羊')
        animal.breathe('猪')


if __name__ == '__main__':
    client = Client()
    client.work()

结果

牛 呼吸空气
羊 呼吸空气
猪 呼吸空气

上述代码实现了一个类Animal,仅仅实现了一个职责---------------breathe。客户端调用后得到上面的结果。

但如果又增加了一种动物-----------鱼,很明显鱼是不能呼吸空气得的,因此要对类Animal进行修改,或者把类直接拆分为两个类分别实现水生动物的breathe和陆生动物的breathe.

改进1:类Animal中增加一个新的方法breathe1

class Animal(object):
    def __init__(self):
        pass

    def breathe(self, name):
        print('%s 呼吸空气' %name)

    def breathe1(self, name):
        print('%s 呼吸水' %name)


# caller
class Client(object):
    def __init__(self):
        pass

    def work(self):
        animal = Animal()
        animal.breathe('牛')
        animal.breathe('羊')
        animal.breathe('猪')
        animal.breathe1('鱼')


if __name__ == '__main__':
    client = Client()
    client.work()

结果

牛 呼吸空气
羊 呼吸空气
猪 呼吸空气
鱼 呼吸水

改进2:把类Animal拆分为两个类分别负责陆生动物呼吸和水生动物呼吸

代码入下:

class Terrestrialanimal(object):

    def __init__(self):
        pass

    def breathe(self, name):
        print('%s 呼吸空气' %name)


class Aquatic(object):

    def __init__(self):
        pass

    def breathe(self, name):
        print('%s 呼吸水' %name)


# caller
class Client(object):
    def __init__(self):
        pass

    def work(self):
        terrestrialanimal = Terrestrialanimal()
        terrestrialanimal.breathe('牛')
        terrestrialanimal.breathe('羊')
        terrestrialanimal.breathe('猪')

        aquatic = Aquatic()
        aquatic.breathe('鱼')


if __name__ == '__main__':
    client = Client()
    client.work()

结果

牛 呼吸空气
羊 呼吸空气
猪 呼吸空气
鱼 呼吸水






猜你喜欢

转载自blog.csdn.net/ruguowoshiyu/article/details/80660183