• 单一职责原则--设计模式系列


    定义

      一个类只负责一项职责

    职责扩散

      什么叫职责扩散,就是职责再进行细化,就拿公司来说,好比客户的需求,需求是不断变化的,而且存在极大的不确定性,说不定哪天上司找到你要重新细化某个需求

      所以最好在职责扩散到我们无法控制的程度之前,立刻对代码进行重构

    栗子

      我们先下面这段代码:

    class Animal:
    
        def __init__(self,name):
            self.name = name
    
        def breathe(self):
            print('%s用肺呼吸'%self.name)
    
    niu = Animal('小奶牛')
    zhu = Animal('小白猪')
    
    niu.breathe()
    zhu.breathe()
    

       我们很快就能从上面代码中发现一些逻辑上的错误,因为不是所有的动物都是用肺呼吸,有的使用腮呼吸的,应该将Animal类细分为陆生动物类Terrestrial,水生动物类Aquatic,代码如下:

    class Animal:
    
        def __init__(self,name):
            self.name = name
    
    class Terrestrial(Animal):
    
        def breathe(self):
            print('%s 用肺呼吸'%self.name)
    
    class Aquatic(Animal):
    
        def breathe(self):
            print('%s 用腮呼吸'%self.name)
    
    
    c = Terrestrial('小花猫')
    c.breathe()
    
    fish = Aquatic('美人鱼')
    fish.breathe()
    

       我们看到上面代码的实现就是动物类分出两类,并把呼吸的方法写入的派生类里,好!这样做是没问题的,那看看下面这段代码:

    class BreatheBehavior:
    
        def breathe(self):pass
    
    class LungBreathe(BreatheBehavior):
    
        def breathe(self):
            print('用肺呼吸')
    
    class CheekBreathe(BreatheBehavior):
    
        def breathe(self):
            print('用腮呼吸')
    
    
    class Animal:
    
        def __init__(self,name,breatheP):
            self.name = name
            self.BreatheParam = breatheP
    
        def performBreathe(self):
            self.BreatheParam.breathe()
    
    class Terrestrial(Animal):
    
        def __init__(self,name,breatheP=LungBreathe()):
            super(Terrestrial,self).__init__(name,breatheP)
    
    class Aquatic(Animal):
    
        def __init__(self,name,breatheP=CheekBreathe()):
            super(Aquatic,self).__init__(name,breatheP)
    
    c = Terrestrial('小花猫')
    c.performBreathe()
    
    fish = Aquatic('美人鱼')
    fish.performBreathe()
    

       我们发现第二种方式,则像是用接口的形式实现了某个行为的类化,你可能会想,第二种方法的代码实现明显长的多,我为什么要用第二种方式。

      在今天的这个例子,毫无疑问是第一方法简单,那我们先来看看用单一职责原则的目的吧:

    • 目的
    1. 可以降低类的复杂度,一个类只负责一项职责,其逻辑肯定要比负责多项职责简单的多
    2. 提高类的可读性,提高程序的可维护性
    3. 变更引起的风险降低,变更是必然的,如果单一职责原则遵守的好,当修改一个功能时,可以显著降低对其他功能的影响
    4. 单一职责原则同时也适用于模块化的程序设计

      好!所以单一职责的核心无非就是降低复杂度和提高可读性以及可扩展性,假如你把要动物的种类细化再细化,按照第一种方法--你是不是要在派生类重写多个呼吸方法?但是动物的呼吸方式无非就是这几种,所以第二种方法更适合复杂的场合,所以每种方法因场景而异,自己把握!

                                   欢迎大家对我的博客内容提出质疑和提问!谢谢

                                                                                 笔者:拍省先生 

  • 相关阅读:
    变量使用的注意事项
    计算机存储单元
    常量
    mybatis报错There is no getter for property named '***' in 'class ***'
    sonar-scanner扫描各种出错解决
    SonarQube搭建的各种问题
    linux每日命令(18):whereis命令
    Django视图层之路由配置系统(urls)
    Django---MTV模型、基本命令、简单配置
    web框架
  • 原文地址:https://www.cnblogs.com/xinsiwei18/p/5699599.html
Copyright © 2020-2023  润新知